【发布时间】:2009-09-07 13:59:52
【问题描述】:
我遇到了一个恼人的问题。这可能是一些愚蠢的事情,但我找不到。
我正在使用 Linq to NHibernate,我想计算存储库中有多少项目。这是我的存储库的一个非常简化的定义,其中包含重要的代码:
public class Repository {
private ISession session;
/* ... */
public virtual IQueryable<Product> GetAll() {
return session.Linq<Product>();
}
}
所有相关代码在问题末尾。
然后,为了计算我的存储库中的项目,我执行以下操作:
var total = productRepository.GetAll().Count();
问题是total 是0。总是。但是,存储库中有项目。此外,我可以.Get(id)其中任何一个。
我的 NHibernate 日志显示执行了以下查询:
SELECT count(*) as y0_ FROM [Product] this_ WHERE not (1=1)
那一定是那个“WHERE not (1=1)”子句导致这个问题的原因。
我可以做些什么来.Count() 我的存储库中的项目?
谢谢!
编辑: 实际上,repository.GetAll() 代码有点不同......这可能会改变一些东西!它实际上是实体的通用存储库。一些实体还实现了 ILogicalDeletable 接口(它包含一个布尔属性“IsDeleted”)。就在 GetAll() 方法中的“返回”之前,我检查我正在查询的实体是否实现 ILogicalDeletable。
public interface IRepository<TEntity, TId> where TEntity : Entity<TEntity, TId> {
IQueryable<TEntity> GetAll();
...
}
public abstract class Repository<TEntity, TId> : IRepository<TEntity, TId>
where TEntity : Entity<TEntity, TId>
{
public virtual IQueryable<TEntity> GetAll()
{
if (typeof (ILogicalDeletable).IsAssignableFrom(typeof (TEntity)))
{
return session.Linq<TEntity>()
.Where(x => (x as ILogicalDeletable).IsDeleted == false);
}
else
{
return session.Linq<TEntity>();
}
}
}
public interface ILogicalDeletable {
bool IsDeleted {get; set;}
}
public Product : Entity<Product, int>, ILogicalDeletable
{ ... }
public IProductRepository : IRepository<Product, int> {}
public ProductRepository : Repository<Product, int>, IProductRepository {}
编辑 2:实际上,.GetAll() 总是为实现 ILogicalDeletable 接口的实体返回一个空的结果集(即,它总是添加一个 WHERE NOT (1=1) 子句。
我认为 Linq to NHibernate 不喜欢这种类型转换。
【问题讨论】:
-
听起来 GetAll 代码实际上非常重要。可以发一下吗?
-
它现在就在那里。我认为 Linq to NHibernate 将 "(x as ILogicalDeletable).IsDeleted == false" 转换为 "NOT (1=1)"。
-
您找到解决方法了吗?我遇到了同样的事情,在我的情况下无法使用过滤器。
标签: linq nhibernate count