Entity Framework: update an object or add if it does not exist

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

+5
source share
3 answers

You must complete the first request no matter what, unfortunately.

, , T-SQL MERGE, , ( ), , .

+2

MVC 3 EF 4 , , :

using (var context = new TestStackOverFlowEntities())
{
    Person p = new Person();
    p.Id = long.Parse(collection["Id"]);
    p.FirstName = collection["FirstName"];
    p.LastName = collection["LastName"];
    context.People.Attach(p);
    context.ObjectStateManager.ChangeObjectState(p, System.Data.EntityState.Modified);
    context.SaveChanges();
    return RedirectToAction("Index");
}

: ,

context.ObjectStateManager.ChangeObjectState(p, System.Data.EntityState.Added);

Id == 0//.. .

:

using (var context = new TestStackOverFlowEntities())
{
    Person p = new Person();                        
    p.Id = 0;
    p.FirstName = collection["FirstName"];
    p.LastName = collection["LastName"];
    context.People.Attach(p);
    context.ObjectStateManager.ChangeObjectState(p, System.Data.EntityState.Added);
    context.SaveChanges();
    return RedirectToAction("Index");
}
0

, :

db.Attach(model);
db.SaveChanges(model);

Will be updated if an existing key exists, and create if it does not.

0
source

All Articles