开发者

MERGE in Entity Framework

开发者 https://www.devze.com 2023-03-01 13:41 出处:网络
Is there a way t开发者_StackOverflowo call T-Sql\'s MERGE command from .NET Entity framework 4?No there no such built-in functionality - you must build your own. Very common is for example approach li

Is there a way t开发者_StackOverflowo call T-Sql's MERGE command from .NET Entity framework 4?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消