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);
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.
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With