views:

345

answers:

1

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, @name)

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

A: 

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.

Programming Hero
thank you very much!!
daniela