开发者

If-exists-UPDATE-else-INSERT with Linq-to-Entities?

is there a way to write this same SQL atomic instruction using Entities and LinQ?

IF EXISTS (SELECT * FROM MyTable WHERE ID = @Id) UPDATE MyTable SET name = @name ELSE INSERT INTO MyTable (@Id, 开发者_StackOverflow中文版@name)

or do you need to call a stored procedure from within the EF?


The Entity Framework keeps track of the lifespan of objects:

  • If the object was initialized from a query, the framework understands a record should exist in the database and will perform an UPDATE when pushing changes back to the database.
  • If the object was initialized in code, the framework understands it as a "new" object and performs an INSERT when pushing the changes to the database.

If you wish to have a single piece of SQL called, regardless of whether an INSERT or UPDATE operation is required, you will have to specify a stored procedure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜