Is there a way to call T-Sql's MERGE command from .NET Entity framework 4?
1 Answer
No there no such built-in functionality - you must build your own. Very common is for example approach like:
public void SaveOrUpdate(MyEntity entity)
{
if (entity.Id == 0)
{
context.MyEntities.AddObject(entity);
}
else
{
context.MyEntities.Attach(entity);
context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
// You can call SaveChanges here or you can call it separately after multiple changes
}
This is example for working with detached entity which have Id
auto generated in the database (IDENTITY
). Default Id for new entity is always 0 because the real value will be assigned during saving changes.
-
thanks, however When using DDD and you are attaching an Aggregate root, with a few levels of nesting of properties, then one would need to do some form or recursion. Is there some example of that? (It also bit puzzling that EF team expects devs to handle this common scenario themselves, when other orms such as NHibernate offer merge out of the box) Apr 25, 2014 at 15:16
-
5But what if you don't already know if the object exists in the database? The
MERGE
statement is precisely for determining if the object exists or not, and updating or inserting as needed. Nov 17, 2014 at 16:49 -
2
-
@JoshuaFrank That's what
if (entity.Id == 0)
is for; presumably in the database Id starts at 1. Aug 24, 2019 at 18:53