I have a scenario where I need to update an object if it exists, or add a new one if it does not work.
I would like to execute one method for this (it would be great if it were one trip to the server).
Is there something similar in EF?
Now my code is as follows:
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 request, 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 should I execute the first request no matter what?
thank
source
share