13

Is there a way to call T-Sql's MERGE command from .NET Entity framework 4?

Chris Moschini
  • 36,764
  • 19
  • 160
  • 190
alerya
  • 3,125
  • 3
  • 28
  • 50

1 Answers1

12

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.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • 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) – Mickey Puri Apr 25 '14 at 15:16
  • 5
    But 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*. – Joshua Frank Nov 17 '14 at 16:49
  • 2
    You miss the delete part. – Azimuth May 16 '17 at 14:25
  • @JoshuaFrank That's what `if (entity.Id == 0)` is for; presumably in the database Id starts at 1. – Tom Blodget Aug 24 '19 at 18:53