【问题标题】:EntityFramework .net 4 Update entity with a simple methodEntityFramework .net 4 用简单的方法更新实体
【发布时间】:2009-08-27 20:16:47
【问题描述】:

我在看这个 SO 问题:ADO.net Entity Framework: Update only certian properties on a detached entity。这对我帮助很大。我现在知道在对其进行更改之前我需要附加一个实体。但是我该怎么做:

我有一个 MVC 网站,一个包含以下字段的客户更新页面:ID、名称、地址等。我的 MVC 正在将其解析为客户实体。如何执行以下操作:

  • 更新我的实体并保存对它的更改。
  • 如果我在加载实体后进行了更改,则捕获异常。

【问题讨论】:

    标签: .net asp.net-mvc entity-framework


    【解决方案1】:

    试试这样的(伪代码,我可能记错了一些方法名):

    public void Update(Customer entity)
    {
    
       using (MyContext ctx = new MyContext())
       {
          // Create a stub entity and attach it
          Customer db = new Customer {ID = entity.ID};
          ctx.Customers.Attach(db); // ctx.AttachTo("Customers", db) in 3.5 sp1
    
          // ApplyPropertyChanges in 3.5 Sp1
          ctx.ApplyCurrentValues(entity); 
          ctx.SaveChanges();
       }
       ...
    }
    

    此代码使用Stub Entity 技巧。如果您有关系需要告诉 EF 更多关于原始实体的信息,请查看上面的博客文章了解更多信息,因为您也可以使用存根来做到这一点。

    或者,如果您根本不关心并发性,您可以这样做:

    public void Update(Customer entity)
    {
       using (MyContext ctx = new MyContext())
       {
          // pull the entity from the database
          Customer db = ctx.Customers.First(c => c.ID == entity.ID);
    
          // ApplyPropertyChanges in 3.5 Sp1
          ctx.ApplyCurrentValues(entity); 
          ctx.SaveChanges();
       }
    }
    

    希望对你有帮助

    亚历克斯·詹姆斯

    Entity Framework Tips

    【讨论】:

    • ApplyCurrentValues() 方法对我来说不存在。
    • @Alex James:感谢 Stub Entity 和 Entity Framework Tips 的链接。这些都是很棒的技巧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多