Cannot .Count() on IQueryable (NHibernate)

Posted by Bruno Reis on Stack Overflow See other posts from Stack Overflow or by Bruno Reis
Published on 2009-09-07T13:59:52Z Indexed on 2010/04/07 5:43 UTC
Read the original article Hit count: 195

Filed under:
|
|

Hello, I'm with an irritating problem. It might be something stupid, but I couldn't find out.

I'm using Linq to NHibernate, and I would like to count how many items are there in a repository. Here is a very simplified definition of my repository, with the code that matters:

public class Repository {
    private ISession session;
    /* ... */
    public virtual IQueryable<Product> GetAll() {
        return session.Linq<Product>();
    }
}

All the relevant code in the end of the question.

Then, to count the items on my repository, I do something like:

var total = productRepository.GetAll().Count();

The problem is that total is 0. Always. However there are items in the repository. Furthermore, I can .Get(id) any of them.

My NHibernate log shows that the following query was executed:

SELECT count(*) as y0_ FROM [Product] this_ WHERE not (1=1)

That must be that "WHERE not (1=1)" clause the cause of this problem.

What can I do to be able .Count() the items in my repository?

Thanks!

EDIT: Actually the repository.GetAll() code is a little bit different... and that might change something! It is actually a generic repository for Entities. Some of the entities implement also the ILogicalDeletable interface (it contains a single bool property "IsDeleted"). Just before the "return" inside the GetAll() method I check if if the Entity I'm querying implements 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 {}

Edit 2: actually the .GetAll() is always returning an empty result-set for entities that implement the ILogicalDeletable interface (ie, it ALWAYS add a WHERE NOT (1=1) clause.

I think Linq to NHibernate does not like the typecast.

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about count