比较两个对象的值而不列出每一列

时间:2017-08-29 06:36:45

标签: c# entity-framework equals

Web服务以业务逻辑Graph.AddressList导入数据和存储。如果找到匹配项,请添加到keepList。 问题是数据完全相同,但没有添加到保留列表中。例如,如果没有写出数据库中的每一列以匹配xmlRecord中的每一列,则填充数据库中的记录中的ENTITYKEY但不在Xml中。有办法解决这个问题吗?

// Fetch List Of Addresses
List<Address> updateAddressList = DbContext.GraphAddressList.Where<Address>(p => p.PersonnelNo == action.PersonnelNo).ToList<Address>();

////IF ADDRESS EXISTS IN THE DB, BUT NOT IN THE XML FILE, REMOVE FROM DB
List<Address> keepList = new List<Address>();
foreach (Address recordInDB in updateAddressList)
{
    foreach (Address_0006 recordInXML in Graph.AddressList)
    {
        if (recordInDB == recordInXML)
        {                                                        
            keepList.Add(recordInDB);
        }
    }
}

List<Address> removeList = updateAddressList.Except(keepList).ToList();
foreach (Address record in removeList)
{                                           
    DbContext.AddressList.DeleteObject(record);
}

感谢您的回复,所以我需要创建一个类

 public override bool Equals(object obj)
{
    var item = obj as RecommendationDTO;

    if (item == null)
    {
        return false;
    }

    return this.RecommendationId.Equals(item.RecommendationId);
}

public override int GetHashCode()
{
    return this.RecommendationId.GetHashCode();
}

2 个答案:

答案 0 :(得分:4)

recordInDBrecordInXML是自定义对象,要检查它们是否相等,您必须:

  1. 为他们覆盖EqualsGetHashCodeCorrect way to override Equals() and GetHashCode()
  2. 实施IEqualityComparerHow to use the IEqualityComparer
  3. 让其中一个类实现IEquatable<T>,其中T是另一个类的类型
  4. 这样做的对象将通过他们拥有的属性进行比较。目前(x == y)检查的是引用是否相等 - 这是两个不同的实例意味着false。执行此操作后,比较时还应使用recordInDB.Equals(recordInXML)

    执行此操作后,您还可以重构一下:

    var keepList = recordInDB.Where(record => Graph.AddressList.Contains(record));
    var removeList = updateAddressList.Except(keepList).ToList();
    foreach (Address record in removeList)
    {                                           
        DbContext.AddressList.DeleteObject(record);
    }
    

    使用选项3,然后在Address_0006中实施IEquatable<Address>

    public class Address_0006 : IEquatable<Address>
    {
        public bool Equals(Address other)
        {
            // Compare here that each of the relevant properties in this (Address_0006) 
            // equals the corresponding property in other (Address)
        }
    }
    

答案 1 :(得分:0)

您可以反映AddressAddress_0006类型的属性,并检查同名命名的属性是否包含相同的数据。但是反射速度相当慢,所以除非你有数百个属性并经常更改,否则我建议手动编写比较。