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のlazyloadはオフになっています。

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 に答える