Asp.net mvc 3 LINQ2SQL实体-仅更新已更改的字段

Asp.net mvc 3 LINQ2SQL实体-仅更新已更改的字段,asp.net-mvc-3,linq-to-sql,Asp.net Mvc 3,Linq To Sql,我希望在我的MVC3项目中有一种更简单的方法来实现这一点。在我的数据库中,我有一个客户表,它通过LINQ2SQL映射到我的应用程序中。还有一个partial customer类,我在其中执行更新、查找等操作,其中我有一个更新方法,如下所示: public static void Update(Customer customer) { if (customer == null) return; using(var db = new DataBaseContext)

我希望在我的MVC3项目中有一种更简单的方法来实现这一点。在我的数据库中,我有一个客户表,它通过LINQ2SQL映射到我的应用程序中。还有一个partial customer类,我在其中执行更新、查找等操作,其中我有一个更新方法,如下所示:

public static void Update(Customer customer)
{
    if (customer == null)
        return;

    using(var db = new DataBaseContext)
    {
        var newCustomer = db.Customers.Where(c => c.customer_id = customer.customer_id).SingleOrDefault();

        if(newCustomer == null) 
            return;

        newCustomer.first_nm = customer.first_nm;
        // ...
        // ...  Lot's of fields to update
        // ...
        newCustomer.phone_num = customer.phone_nm;

        db.SubmitChanges();
    }
}
我希望找到一种不那么麻烦的方法,用customer中不同的对应字段更新newCustomer中的字段

有什么建议吗?谢谢。

我认为您可以实施:

或者实现
ICloneable
并将
newCustomer
设置为
customer.Clone()
。那么就不需要附加
customer
,因为
newCustomer
已经附加了

在EF(4.1)中,我认为您只需将实体附加为修改后的实体:

  myDbContext.Customers.AttachAsModified(customer, this.ChangeSet.GetOriginal(customer), myContext);
更新:
看起来L2S需要实体的原始值。在回复您的评论时,您有两种选择:使用时间戳列、返回实体子集或将原始实体放在手中。在您的场景中,您已经拥有原始实体:

// This is your original entity
var newCustomer = db.Customers.Where(c => c.customer_id = customer.customer_id).SingleOrDefault();  
因此,您很可能会:

if (customer != newCustomer)
{
     myDbContext.Customers.Attach(customer, newCustomer);
}  
注意:如果我是你,我会将
newCustomer
重命名为
originalCustomer
,因为它与实体的状态更相关


这种方法的问题是,为了获得原始客户,您需要额外访问数据库(
newCustomer
)。请看一看,并明确了解如何使用时间戳列来防止额外的数据库跳闸。

我的代码使用attach方法,但失败,返回一个“如果实体声明版本成员或没有更新检查策略,则只能将其作为修改的实体进行附加,而不返回原始状态。”错误
// This is your original entity
var newCustomer = db.Customers.Where(c => c.customer_id = customer.customer_id).SingleOrDefault();  
if (customer != newCustomer)
{
     myDbContext.Customers.Attach(customer, newCustomer);
}