CompositeId并覆盖了GetHashCode()和Equals()方法

时间:2013-05-22 12:08:13

标签: asp.net nhibernate entity equals gethashcode

我有实体类:

    [Serializable, Class(Table = "mon.tableView", Lazy = false)]
    public class TableView
    {
    [CompositeId(1)]
    [KeyProperty(2, Name = "column1", Column = "column1", TypeType = typeof(int))]
    [KeyProperty(3, Name = "column2", Column = "column2", TypeType = typeof(int))]
    internal int VirtualId { get; set; }

    [Property(Column = "column1")]
    private int column1 { get; set; }

    [Property(Column = "column2")]
    public int? column2 { get; set; }

    [Property(Column = "column3")]
    public int column3 { get; set; }

    [Property(Column = "otherColumn")]
    public string otherColumn{ get; set; }

    public override bool Equals(object other)
    {
        if (this == other)
            return true;

        TableViewv dp = other as TableView;

        if (vdp == null)
            return false; // null or not a ReadOnlyUserRole

        return column1.Equals(vdp.column1) ^ column2.Equals(vdp.column2) && column3.Equals(vdp.column3) && otherColumn.Equals(vdp.otherColumn);        }

    public override int GetHashCode()
    {
        return column1.GetHashCode() ^ column2.GetHashCode();
    }
}

我知道GetHashCode()给出了2个答案: - 当2个物体不相等时,我们知道它们不相等。 - 当2个物体相等时,它们可能相等但不确定。 因此,有这样的Equal()方法。

GetHashCode()方法为2个对象提供了相同的整数,但我知道其他属性不相等。当我得到列表这些对象我有几次重复的对象,我的问题是调用Equals()方法?因为在调用此方法时我从未在调试模式下看到过。

1 个答案:

答案 0 :(得分:0)

你的GetHashCode实现看起来是正确的,但你的equals似乎有问题,你应该只比较compositkeys,column1和column2(可空)的值:

public override bool Equals(object other)
{
    if (this == other)
        return true;

    TableViewv dp = other as TableView;

    if (vdp == null)
        return false; // null or not a ReadOnlyUserRole


    return column1 == vdp.column1 &&
            ( (!column2.HasValue && !vdp.column2.HasValue ) || (column2.HasValue && vdp.column2.HasValue && column2.Value == vdp.column2.Value ));    
}