If a row already exists, update it; otherwise, insert logic using Entity Framework.

c# entity-framework

Question

Does anybody have recommendations on the most effective approach to use Entity Framework to accomplish the "update row if it exists otherwise insert" logic?

1
177
4/5/2011 8:06:21 PM

Accepted Answer

Simply use the following syntax if you are dealing with an attached object (an object loaded from the same instance of the context):

if (context.ObjectStateManager.GetObjectStateEntry(myEntity).State == EntityState.Detached)
{
    context.MyEntities.AddObject(myEntity);
}

// Attached object tracks modifications automatically

context.SaveChanges();

If you have any knowledge about the key to the item, you may use something like this:

if (myEntity.Id != 0)
{
    context.MyEntities.Attach(myEntity);
    context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
    context.MyEntities.AddObject(myEntity);
}

context.SaveChanges();

If the object's Id can't be used to determine its existence, you must do a lookup.

var id = myEntity.Id;
if (context.MyEntities.Any(e => e.Id == id))
{
    context.MyEntities.Attach(myEntity);
    context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
    context.MyEntities.AddObject(myEntity);
}

context.SaveChanges();
173
4/5/2011 9:29:45 PM

Popular Answer

There is an update to Entity Framework 4.3 thatAddOrUpdate at namespace methodSystem.Data.Entity.Migrations :

public static void AddOrUpdate<TEntity>(
    this IDbSet<TEntity> set,
    params TEntity[] entities
)
where TEntity : class

which according to the 17-zzz

Adds or updates entities by key when SaveChanges is called. Equivalent to an "upsert" operation from database terminology. This method can be useful when seeding data using Migrations.


I'll copy and paste the pertinent sections of the URL that @Colin gave to address the remark from @Smashing1978.

The job of AddOrUpdate is to ensure that you don’t create duplicates when you seed data during development.

First, it will execute a query in your database looking for a record where whatever you supplied as a key (first parameter) matches the mapped column value (or values) supplied in the AddOrUpdate. So this is a little loosey-goosey for matching but perfectly fine for seeding design time data.

More importantly, if a match is found then the update will update all and null out any that weren’t in your AddOrUpdate.

However, because my local data for consumers is read-only, I am in a scenario where I am taking data from an external service and adding or modifying existing values by primary key.AddOrUpdate producing for more than 6 months with no issues to yet.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow