检查实体是否具有相同的属性

时间:2012-11-24 15:16:55

标签: c# entity-framework-4

我有点发酵,我会在这里描述一下。我有一个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 / strong>即可。我认为这是为什么它不起作用。 EntityKey 不能设置为null。

有关如何执行此操作的任何想法,而无需手动检查所有属性(实际上是我的情况下为25+)?

1 个答案:

答案 0 :(得分: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;
}