Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: Update entity or add if it doesn't exist

I have a scenario where I have to update an entity if it exists or add a new one if it doesn't.

I would like to execute a single method for this (it would be great if it were a single trip to the server).

Is there something like that in EF?

Right now my code looks like this:

var entity = db.Entities.FirstOrDefault(e => e.Id == myId);
if (entity == null)
{
    entity = db.Entities.CreateObject();
    entity.Id = myId;
}

entity.Value = "my modified value";

db.SaveChanges();

But I would like to avoid the first query, something like this:

var entity = new Entity();
entity.Id = myId;
entity.Value = "my modified value";
db.AddOrAttach(entity);
db.SaveChanges();

Is there anything similar? or do I have to perform the first query no matter what?

Thanks

like image 979
willvv Avatar asked Nov 04 '22 19:11

willvv


1 Answers

You have to perform the first query no matter what, unfortunately.

One option would be to write a stored procedure that performs a T-SQL MERGE then map it to a function import, though that would require that you pass the scalar values of the entity as parameters (and support for navigation properties would be done), but it would accomplish what you're after.

like image 108
Adam Robinson Avatar answered Nov 09 '22 08:11

Adam Robinson