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 は、entryで null に設定されているalreadyInsertedの null 以外のEntityKeyプロパティを作成します。それが機能しない理由だと思います。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 に答える