Question

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

1
11
12/3/2014 4:34:44 PM

Accepted 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.

11
4/30/2011 2:57:58 PM


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