【发布时间】:2012-06-20 15:07:13
【问题描述】:
我有一个使用 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 已关闭延迟加载。
【问题讨论】:
-
那会是什么样子? TId 是一个通用参数...
-
标准标准 api 采用通用对象
-
我认为您可以重新制定它以使用例如WhereRestrictionOn() 和 Restrictions.Eq() 避免提及 Equals。
-
顺便说一句,在每个存储库方法中打开一个新会话通常是一个很大的禁忌,因为它会妨碍正确使用缓存、延迟加载和事务。
标签: c# nhibernate