开发者

Entity Framework 4 update and insert one function

I'm migrating from SubSonic to EF4. In SubSonic开发者_Go百科 models had a function called Save, if the key of the model was 0 an insert was done, otherwise an update.

Is there a way to make a generic Save function like in SubSonic? For exmaple using an extension method?


Yes but you have to do it yourselves. Try something like this:

public interface IEntity
{
  int Id { get; set; }
}

...

public void SaveOrUpdate<T>(T entity) where T : IEntity
{
  using (var context = new MyContext())
  {
    if (entity.Id == 0)
    {
      context.AddObject(entity);
    }
    else
    {
      context.Attach(entity);
      context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
    }

    context.SaveChanges();
  }
}


I think a little bit better version will be public static void SaveOrUpdate(this T entity) where T : IEntity

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜