我们应该如何为NHibernate实体实现Equals和GetHashCode

时间:2012-06-29 13:31:33

标签: .net nhibernate equals gethashcode

这个问题有很多问题和答案以及文章,但我认为似乎没有真正明确/正确的答案

对我而言,Ayende迄今为止已经看到了最好的通用实现:http://ayende.com/blog/2500/generic-entity-equality

....但是从2007年开始....

这是实现这些方法的“最佳方式”,尤其是NHibernate 3.2,它在代理实现方面与早期版本存在一些差异吗?

3 个答案:

答案 0 :(得分:5)

是!

您应该覆盖EqualsGetHashCode。但是,你不应该值相等Name == other.Name && Age == other.Age),你应该做同一性身份!

如果不这样做,您很可能会将实体的代理与真实实体进行比较,并且可以调试。例如:

public class Blog : EntityBase<Blog>
{
    public virtual string Name { get; set; }

    // This would be configured to lazy-load.
    public virtual IList<Post> Posts { get; protected set; }

    public Blog()
    {
        Posts = new List<Post>();
    }

    public virtual Post AddPost(string title, string body)
    {
        var post = new Post() { Title = title, Body = body, Blog = this };
        Posts.Add(post);
        return post;
    }
}

public class Post : EntityBase<Post>
{
    public virtual string Title { get; set; }
    public virtual string Body { get; set; }
    public virtual Blog Blog { get; set; }

    public virtual bool Remove()
    {
        return Blog.Posts.Remove(this);
    }
}

void Main(string[] args)
{
    var post = session.Load<Post>(postId);

    // If we didn't override Equals, the comparisons for
    // "Blog.Posts.Remove(this)" would all fail because of reference equality. 
    // We'd end up be comparing "this" typeof(Post) with a collection of
    // typeof(PostProxy)!
    post.Remove();

    // If we *didn't* override Equals and *just* did 
    // "post.Blog.Posts.Remove(post)", it'd work because we'd be comparing 
    // typeof(PostProxy) with a collection of typeof(PostProxy) (reference 
    // equality would pass!).
}

如果您使用int作为Id(也可以抽象为any identity type),这是一个示例基类:

public abstract class EntityBase<T>
    where T : EntityBase<T>
{
    public virtual int Id { get; protected set; }

    protected bool IsTransient { get { return Id == 0; } }

    public override bool Equals(object obj)
    {
        return EntityEquals(obj as EntityBase<T>);
    }

    protected bool EntityEquals(EntityBase<T> other)
    {
        if (other == null)
        {
            return false;
        }
        // One entity is transient and the other is not.
        else if (IsTransient ^ other.IsTransient)
        {
            return false;
        }
        // Both entities are not saved.
        else if (IsTransient && other.IsTransient)
        {
            return ReferenceEquals(this, other);
        }
        else
        {
            // Compare transient instances.
            return Id == other.Id;
        }
    }

    // The hash code is cached because a requirement of a hash code is that
    // it does not change once calculated. For example, if this entity was
    // added to a hashed collection when transient and then saved, we need
    // the same hash code or else it could get lost because it would no 
    // longer live in the same bin.
    private int? cachedHashCode;

    public override int GetHashCode()
    {
        if (cachedHashCode.HasValue) return cachedHashCode.Value;

        cachedHashCode = IsTransient ? base.GetHashCode() : Id.GetHashCode();
        return cachedHashCode.Value;
    }

    // Maintain equality operator semantics for entities.
    public static bool operator ==(EntityBase<T> x, EntityBase<T> y)
    {
        // By default, == and Equals compares references. In order to 
        // maintain these semantics with entities, we need to compare by 
        // identity value. The Equals(x, y) override is used to guard 
        // against null values; it then calls EntityEquals().
        return Object.Equals(x, y);
    }

    // Maintain inequality operator semantics for entities. 
    public static bool operator !=(EntityBase<T> x, EntityBase<T> y)
    {
        return !(x == y);
    }
}

答案 1 :(得分:2)

我个人的建议是根本不要实施这些方法,因为这样做会在很多情况下强制加载。

此外,如果您不跨会话移动实体,您将永远不需要这样。即使你这样做,也可以在需要的时候通过Id进行比较。

答案 2 :(得分:1)

我在实施@TheCloudlessSky建议的解决方案时遇到了多个问题。

首先,我的ID没有一致的数据类型;有些是Sub copyformuladown14() copyRange As Range 'Set range variable to F6 on sheet1 Set copyRange = Sheet1.Range("F6") 'Starting at row 20, loop every 14 rows and paste 'you have to monkey with number "20" For i = 20 To 2533 Step 14 copyRange.Copy Destination:=Sheet1.Range("F6").Offset(i) Next i End Sub ,有些是int,有些是Guid。此外,一些是自动生成的,而另一些是手动分配的。如果我决定使用复合ID,将来可能会出现其他问题。因此,我不能把

string
<{1>}基类中的

。我必须在各自具体的实体类中定义它。

其次,因为我在基类中没有public virtual int Id { get; protected set; } ,所以实现EntityBase属性变得越来越难。

所以,我决定为每个实例生成Id并使用它来实现bool IsTransientGuid,如下所示:

GetHashCode