Entity Framework 4 更新并插入一项功能 [英] Entity Framework 4 update and insert one function

查看:34
本文介绍了Entity Framework 4 更新并插入一项功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 SubSonic 迁移到 EF4.在 SubSonic 模型中有一个名为 Save 的函数,如果模型的键为 0,则插入完成,否则更新.

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.

有没有办法像 SubSonic 一样制作通用的保存功能?例如使用扩展方法?

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

这篇关于Entity Framework 4 更新并插入一项功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆