2011-09-13 21 views
2

私のMVC 3プロジェクトでこれを行う簡単な方法があると思っていました。私のデータベースには、LINQ2SQLを介してアプリケーションにマッピングされたCustomerテーブルがあります。私は更新を行う部分顧客クラス、ルックアップなどもあります - 私はこのような更新方法があります:LINQ2SQLエンティティ - 変更されたフィールドのみを更新する

私はフィールドを更新するために、あまり面倒な方法であった見つけることを期待していた何
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(); 
    } 
} 

顧客の対応するフィールドが異なるnewCustomerにあります。

提案がありますか?ありがとう。

答えて

1

私はあなたがIEqualityComparerを実装することができると思います。

public class Customer 
{ 
    public string first_nm { get; set; } 
    public int phone_num { get; set; } 
}   
class CustomerComparer : IEqualityComparer<Customer> 
{ 
    public bool Equals(Customer x, Customer y) 
    { 
     //Check whether the compared objects reference the same data. 
     if (Object.ReferenceEquals(x, y)) return true; 

     //Check whether any of the compared objects is null. 
     if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) 
      return false; 

     //Check whether the customer' properties are equal. 
     return x.first_nm == y.first_nm && x.phone_num == y.phone_num ; 
    } 
} 

と、次のようにそれを行う:

if (newCustomer != customer) 
{ 
    myDbContext.Customers.Attach(customer,true); // true means modified. 
} 

またはICloneableを実装し、customer.Clone()newCustomerを設定します。 newCustomerが既に添付されているため、customerを添付する必要はありません。 EF(4.1)で

、私はあなただけの修正などのエンティティを添付しなければならないと思う:

myDbContext.Customers.AttachAsModified(customer, this.ChangeSet.GetOriginal(customer), myContext); 

UPDATE:L2Sは、エンティティの元の値を必要とするよう
まあ、それはそうです。あなたのコメントに応じて、タイムスタンプの列を使用するか、エンティティのサブセットを返すか、元のエンティティを手に持つかの2つの選択肢があります。あなたのシナリオでは、すでに元のエンティティを持っている:

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

注:私はあなただったら、それは複数の関連ですので、私はoriginalCustomerからnewCustomerの名前を変更したいですエンティティの状態に変換します。

このアプローチの問題は、元の顧客(コード内にはnewCustomer)を取得するための追加のデータベースへの移動です。 herehere、間違いなくhereを見て、TimeStamp列を使用して余分なデータベーストリップを防ぐ方法を確認してください。

+0

私のコードはattachメソッドに到達しますが、失敗します。「エンティティは、バージョンメンバーを宣言しているか、または更新チェックポリシーを持っていない場合、元の状態なしでのみ変更できます。エラー –

+0

答えを更新しました。 – Kamyar

関連する問題