Entity Framework 4更新和插入一个函数

发布于 2024-09-17 10:03:47 字数 128 浏览 3 评论 0原文

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

为你鎻心 2024-09-24 10:03:47

是的,但你必须自己做。尝试这样的事情:

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

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();
  }
}
九歌凝 2024-09-24 10:03:47

我认为更好的版本会是
公共静态无效SaveOrUpdate(此T实体)其中T:IEntity

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文