开发者

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


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.


I ran some quick test code for editing in MVC 3 with EF 4 and it seems to work for edit with following code:

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");
}

Edit: I checked with creating new object too, you need to change this

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

when Id == 0 //ie new object.

Quick and dirty code to add new is this:

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");
}


If you are just trying to limit code to clarify your controllers:

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

Will update if the Entity Key exists, and create if it does not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜