Entity Framework 4 update and insert one function

巧了我就是萌 提交于 2019-12-21 06:38:11

问题


I'm migrating from SubSonic to EF4. In SubSonic 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?


回答1:


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();
  }
}



回答2:


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



来源:https://stackoverflow.com/questions/3654332/entity-framework-4-update-and-insert-one-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!