2012-11-24 3 views
0

나는 약간의 피클에 들어 있으며 여기에서 설명 할 것입니다. 내 테이블에 행을 삽입하는 foreach 루프가 있습니다. 그러나 삽입하기 전에 동일한 ID가있는 행이 이미 있는지 확인하고 다른 행의 속성 (열)이 동일한 값인 경우 해당 행이 있는지 확인하고 싶습니다. 엔티티가 동일한 속성을 가지고 있는지 확인하십시오.

내가 할 것입니다 :

var sourceList = LoadFromOtherDataBase(); 
var res = ListAll(); // Load all rows from database which were already inserted... 


foreach (Whatever w in sourceList) 
{ 
    Entry entry = new Entry(); 

    entry.id = w.id; 
    entry.field1 = w.firstfield; 
    entry.field2 = w.secondfield; 
    //so on... 

    //Now, check if this entry was already inserted into the table... 

    var check = res.Where(n => n.id == entry.id); 

    if (check.Count() > 0) 
    { 
    var alreadyInserted = res.Single(n => n.id == entry.id); 
    //Here, I need to see if 'alreadyInserted' has the same properties as 'entry' and act upon it. If same properties, do nothing, otherwise, update alreadyInserted with entry's values. 
    } 
    else 
    { 
     //Then I'll insert it as a new row obviously.... 
    } 


} 

내가 Object.Equals의 생각()하지만 엔티티 프레임 워크가 에 널 (null)로 설정되어 에 대한을 alreadyInserted null이 아닌 EntityKey 속성을 생성 항목. 나는 이것이 작동하지 않는 이유라고 생각한다. EntityKey을 null로 설정할 수 없습니다.

손으로 모든 속성 (실제로는 내 경우 25 개)을 확인하지 않고이 작업을 수행하는 방법에 대한 아이디어가 있습니까?

답변

2

당신은 다음과 같은 반사를 사용할 수 있습니다

/// <summary> 
/// Check that properties are equal for two instances 
/// </summary> 
/// <typeparam name="T"></typeparam> 
/// <param name="first"></param> 
/// <param name="other"></param> 
/// <param name="skipPropeties">A list of names for properties not to check for equality</param> 
/// <returns></returns> 
public static bool PropertiesEquals<T>(this T first, T other, string[] skipPropeties=null) where T : class 
{ 
    var type = typeof (T); 
    if(skipPropeties==null) 
     skipPropeties=new string[0]; 
    if(skipPropeties.Except(type.GetProperties().Select(x=>x.Name)).Any()) 
     throw new ArgumentException("Type does not contain property to skip"); 
    var propertyInfos = type.GetProperties() 
           .Except(type.GetProperties().Where(x=> skipPropeties.Contains(x.Name))); 
    foreach (PropertyInfo propertyInfo in propertyInfos) 
    { 
     if (!Equals(propertyInfo.GetValue(first, null), 
        propertyInfo.GetValue(other, null))) 
      return false; 
    } 
    return true; 
} 
+0

예, 우수. 왜 내가 그걸 생각하지 않았는지 모르겠다. if 값 앞에 다음을 추가했습니다. if (propertyInfo.Name! = "EntityState"&& propertyInfo.Name! = "EntityKey"). –

관련 문제