开发者

Cast problem with LINQ

I'm tring to get my product's types to a list with Linq.

var types = (from t in NHibernateSession.Linq<Product>()
             select t.ProductType).Distinct().ToList<ProductType>();         
return types;

But its giving an Unable to cast object of type error

'...Domain.Product' to type '...Domain.ProductType'.

ProductType is a property of Product.

<many-to-one name="ProductType" class="Portal.Domain.ProductType, TilePortal.Domain" column="ProductTypeID" not-null="true" ></many-to-one>

Edit: It seems like Linq to Nhibernate is not mature enough to handle such queries. I simply want to be able to create a simple SQL query that fetch distinct ProductType's from DB 开发者_JAVA技巧without bringing all products which is no-go for a production db that has millions of products. So if you can illustrate how to do this using HQL os Criteria API that will also do..


You might be running into an issue with the nHibernate LINQ implementation. Do you get the same error with:

 var types = (from t in NHibernateSession.Linq<Product>()
              select t.Type);

If not, what happens when you try using the non-generic ToList()?

 var types = (from t in NHibernateSession.Linq<Product>()
              select t.Type).Distinct().ToList();

As an aside, I'd generally avoid creating a class with a name that conflicts with something in the .NET framework, especially such a basic one as Type. It can only lead to confusion. Perhaps you should rename it ProductType.


I'm pretty sure the linq 2 nh implementation doesn't support this kind of thing yet. You will probably have to execute the sql first and then select the type reference. Like this:

var types = (from t in NHibernateSession.Linq<Product>()
         select t).ToList().Select(t => t.Type).Distinct().ToList<Type>();         
return types;

If you are not using the latest version of the provider, please update and try your example again. If it's implemented it should work fine.

Update

If the only thing you want to do is get all product types. Why not just write this simple query?

var types = (from t in NHibernateSession.Linq<ProductType>()
         select t).ToList();

There is no need to query your products when you need the types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜