【问题标题】:CompositeId and overrided GetHashCode() and Equals() methodsCompositeId 和覆盖的 GetHashCode() 和 Equals() 方法
【发布时间】:2013-05-22 12:08:13
【问题描述】:

我有实体类:

    [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() 方法?因为我从来没有在调试模式下看到过这个方法被调用的时候。

【问题讨论】:

    标签: asp.net nhibernate entity equals gethashcode


    【解决方案1】:

    您的 GetHashCode 实现看起来正确,但您的 equals 似乎有问题,您应该只比较复合键 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 ));    
    }
    

    【讨论】:

    • 感谢您的建议:) 但我的主要观点是何时调用 Equals() 方法,.Net GetHashCode() 方法和 Nhibernate GetHashCode() 之间有什么区别吗?当 2 个对象具有相同的哈希码时,我从未见过调用 Eqals() 方法。
    • NHibernate 依赖于 Equals,如果你实现它错误,NHibernate 将无法正常工作。例如,如果您查询同一个对象两次(NHibernate 的同一个对象具有相同的 fkey),这取决于您的 Equals 实现。 GetHashCode 不能替代 Equals 方法,当您有两个具有相同 HashCode 的对象时会调用它。
    猜你喜欢
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多