Implementing if-not-exists-insert using Entity Framework without race conditions

前端 未结 2 1678
心在旅途
心在旅途 2021-02-01 07:51

Using LINQ-to-Entities 4.0, is there a correct pattern or construct for safely implementing \"if not exists then insert\"?

For example, I currently have a table that tra

2条回答
  •  既然无缘
    2021-02-01 08:31

    You can also write a stored procedure that uses some new tricks from sql 2005+

    Use your combined unique ID (userID + articleID) in an update statement, then use the @@RowCount function to see if the row count > 0 if it's 1 (or more), the update has found a row matching your userID and ArticleID, if it's 0, then you're all clear to insert.

    e.g.

    Update tablex set userID = @UserID, ArticleID = @ArticleID (you could have more properties here, as long as the where holds a combined unique ID) where userID = @UserID and ArticleID = @ArticleID

    if (@@RowCount = 0) Begin Insert Into tablex ... End

    Best of all, it's all done in one call, so you don't have to first compare the data and then determine if you should insert. And of course it will stop any dulplicate inserts and won't throw any errors (gracefully?)

提交回复
热议问题