簡體   English   中英

檢查實體是否具有相同的屬性

[英]Check if the entities have same properties

我有點發酵,我會在這里描述一下。 我有一個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(),但實體框架為alreadyInserted創建了一個非null的EntityKey屬性,在入口中設置為null。 我認為這是為什么它不起作用。 EntityKey不能設置為null。

關於如何做到這一點的任何想法,而不必手動檢查所有屬性(實際上是我的情況下25+)?

您可以使用這樣的反射:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM