通用NHibernate存储库包含(TId id)方法

时间:2012-06-20 15:07:14

标签: c# nhibernate

我有一个使用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>

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

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在我的情况下关闭了lazyload。

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分: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));
    }
}