1

我有一个使用 NHibernate 的通用存储库,其中 ID 的类型也是通用参数:

/// <summary>
/// Represents a common base class for repositories.
/// </summary>
/// <typeparam name="TEntity"> The type of the entity. </typeparam>
/// <typeparam name="TId"> The type of the ID of the entity. </typeparam>
public abstract class RepositoryBase<TEntity, TId> : IRepository<TEntity, TId> where TEntity : EntityBase<TEntity, TId>

在这种情况下,如何实现一个Contains对 NHibernate 快速且可读的通用方法?

public bool Contains(TId id)
{
    using (var session = NHibernateHelper.OpenSession())
    {
        // throws an excpetion that Equals is not supported
        return session.QueryOver<TEntity>().Where(e => e.Id.Equals(id)).RowCount() > 0;
    }
}

更新:

在我的情况下,NHibernate 已经关闭了延迟加载。

4

2 回答 2

2

正如评论中所指出的......使用标准,使用“id”特殊属性

public bool Contains(TId id)
{
    using (var session = NHibernateHelper.OpenSession())
    { 
        return session.CreateCriteria(typeof(TEntity))
            .Add(Expression.Eq("id", id))
            .SetProjection( Projections.Count("id"))
            .UniqueResult() > 0
    }
}
于 2012-06-20T15:18:01.413 回答
0

我认为您必须Eqauls在实体基类中覆盖 和其他比较运算符,例如:

public abstract class TEntity
{
    public override bool Equals(object entity)
    {
        return entity != null
            && entity is EntityBase
            && this == (EntityBase)entity;
    }

    public static bool operator ==(EntityBase base1, 
        EntityBase base2)
    {
        if ((object)base1 == null && (object)base2 == null)
        {
            return true;
        }

        if ((object)base1 == null || (object)base2 == null)
        {
            return false;
        }
        if (base1.Key != base2.Key)
        {
            return false;
        }

        return true;
    }
    public static bool operator !=(EntityBase base1, 
        EntityBase base2)
    {
        return (!(base1 == base2));
    }
}
于 2012-06-20T15:41:13.957 回答