2011-09-13 7 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에 있습니다.

제안 사항? 감사.

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

을하고 다음과 같이 수행합니다 :

답변

1

난 당신이 IEqualityComparer을 구현할 수 있다고 생각

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

또는 ICloneable을 구현하고 customer.Clone()newCustomer을 설정합니다. newCustomer이 이미 첨부되어 있으므로 customer을 첨부 할 필요가 없습니다. EF의

(4.1), I는 수정 같이 그냥 개체를 첨부 할 것 같아요 :

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

UPDATE : 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); 
} 

참고 : 더 관련이 있기 때문에 내가 당신이라면 나는 originalCustomernewCustomer의 이름을 바꿀 것 시나리오에서, 당신은 이미 원래의 실체를 기업의 상태로.

이 접근법의 문제점은 원본 고객 (코드에 newCustomer)을 얻으려면 데이터베이스를 추가로 방문해야한다는 것입니다. here, here 및 확실히 here을보고 TimeStamp 열을 사용하여 여분의 데이터베이스 트립을 방지하는 방법을 확인하십시오.

+0

내 코드가 attach 메소드를 가져 오지만 실패합니다. "버전 구성원을 선언했거나 업데이트 확인 정책이없는 경우 엔티티를 원래 상태로만 수정하여 첨부 할 수 있습니다." 오류 –

+0

답변을 업데이트했습니다. – Kamyar

관련 문제