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.
精彩评论