2012-11-24 86 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(),但實體框架創建一個非空的EntityKey屬性alreadyInserted,其設置爲null在條目。我認爲這是爲什麼它不起作用。 EntityKey不能設置爲空。

任何想法如何做到這一點,而無需手動檢查所有屬性(實際上是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」),因爲這些不需要檢查。 –

相關問題