views:

31

answers:

2

Hi,

I've rammed into a huge problem. I got to these two objects: IList<Product> products; and Collection collection;

Both objects contains and IList<Tag> named .Tags.

I'm trying to do the this with Linq To NHibernate:

products = products.Where(p => p.Tags.Any(t => collection.Tags.Contains(t)));

This will give an exception, because Linq To NHibernate don't support this. But how can I accomplish this? I just can't find any smart way to only get the products that contains the tags that the specific collection has.

Thanks in advance!

Btw, the problem seems very similar to http://stackoverflow.com/questions/2126591/iqueryable-contains-any-of-string-array, but in my scenario I don't want to compare with a string array, but with a collection of poco objects.

[EDIT] I found out that it throws this exception: Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'System.Linq.Expressions.LambdaExpression'.

Alternative ways to resolve the issue is welcome too (HQL etc).

Thanks! [/EDIT]

A: 

What's the underlying type of collection.Tags? It may be that LINQ to NH doesn't like that type, or that it doesn't understand accessing the Tags property. Does this work?

var tags = collection.Tags.ToList();
products = products.Where(p => p.Tags.Any(t => tags.Contains(t)));
dahlbyk
Thanks for your answer! I've tried it, but I get the same result - an null exception as soon as I access the products collection. The code compiles, it's first at runtime (when I request the results) it throws the exception.
J. Hovgaard
A quick update:I added a foreach loop after your code, and now I get a more interesting exception: Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'System.Linq.Expressions.LambdaExpression'.
J. Hovgaard
A: 

Alright, I ended up with a little boring solution, but it works. If anyone hit the same problem: products = _productRepository.Session().CreateSQLQuery( "SELECT {p.*} FROM Products p WHERE (SELECT COUNT(TagId) FROM ProductTags WHERE ProductId = p.Id AND TagId IN (SELECT TagId FROM CollectionTags WHERE CollectionId = :collectionId)) > 0 AND (ShopId = :shopId)") .AddEntity("p", typeof(Product)) .SetInt32("collectionId", collection.Id) .SetInt32("shopId", collection.Shop.Id) .SetResultTransformer(NHibernate.Transform.Transformers.DistinctRootEntity) .List<Product>().AsQueryable();

J. Hovgaard