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() 但 Entity Framework 为alreadyInserted创建了一个非 null EntityKey属性,该属性在entry中设置为 null 。我认为这就是为什么它不起作用。EntityKey不能设置为 null。

关于如何做到这一点的任何想法,而不必手动检查所有属性(在我的情况下实际上是 25+)?

4

1 回答 1

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;
}
于 2012-11-24T15:31:16.717 回答