Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I upsert a record in ADO.NET EF 4.1?

I'm trying to accomplish something really simple and I can't find how to do it using Entity Framework 4.1.

I want a controller method that accepts an object and then does an UPSERT (either an insert or update depending on whether the record exists in the database).

I am using a natural key, so there's no way for me to look at my POCO and tell if it's new or not.

This is how I am doing it, and it seems wrong to me:

[HttpPost]
public JsonResult SaveMyEntity(MyEntity entity)
{            
    MyContainer db = new MyContainer(); // DbContext
    if (ModelState.IsValid)
    {
        var existing =
            db.MyEntitys.Find(entity.MyKey);
        if (existing == null)
        {
            db.MyEntitys.Add(entity);
        }
        else
        {
            existing.A = entity.A;
            existing.B = entity.B;
            db.Entry(existing).State = EntityState.Modified;
        }
        db.SaveChanges();
        return Json(new { Result = "Success" });
    }
}

Ideally, the whole thing would just be something like this:

db.MyEntities.AddOrModify(entity);
like image 366
Eric Z Beard Avatar asked Jun 28 '11 17:06

Eric Z Beard


People also ask

How do I update a single row in Entity Framework?

We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we already have the entity with use. Hence all we need to is to attach/add it to the context.

How do I update table data in Entity Framework?

The steps to update an existing entity are quite simple. First retrieve an instance of the entity from the EntitySet<T> (in our case ObjectSet<Customer>), then edit the properties of the Entity and finally call SaveChanges() on the context.

How do I add a record in Entity Framework?

Use the DbSet. Add method to add a new entity to a context (instance of DbContext ), which will insert a new record in the database when you call the SaveChanges() method. In the above example, context.


1 Answers

Unfortunately there is no way to do this without querying database or using stored procedure. The minimalistic code should be:

public void AddOrModify<T>(T entity, string key) where T : class, IEntity // Implements MyKey 
{
     using (var context = new MyContainer())
     {
         if (context.Set<T>().Any(e => e.MyKey == key))
         {
              context.Entry(entity).State = EntityState.Modified;
         } 
         else
         {
              context.Entry(entity).State = EntityState.Added;
         }

         context.SaveChanges();
     }
}
like image 96
Ladislav Mrnka Avatar answered Sep 20 '22 20:09

Ladislav Mrnka