How do you deal with Linq to NHibernate's Fetch exception when selecting aggregates?
Asked Answered
T

1

7

I'm using LINQ to NHibernate's IQueryable implementation on a asp.net mvc Grid (telerik specifically), where I know I'll need to fetch something eagerly for this particular grid.

So I have query that looks something like this:

var query =  from s in repository.Query<MyClass>()
                     orderby s.Property.Name, s.Name
                     select s;

query = query.Fetch(x => x.Property);

Now, if I execute query.ToList(), everything is fine, and I can verify that it works in an integration test.

It's awesome.

However, if I execute query.Count() or something else that aggregates the query, I get an exception:

Query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=0,role=,tableName=[Property],tableAlias=property1,origin=MyClass myclass0_,colums={myclass0_.PropertyGuid ,className=Property}}] [.Count(.Fetch(.ThenBy(.OrderBy(NHibernate.Linq.NhQueryable`1[MyClass], Quote((s, ) => (s.Property.Name)), ), Quote((s, ) => (s.Name)), ), Quote((x, ) => (x.Property)), ), )]

I know that it's trying to tell me that I can't eagerly fetch Property because MyClass isn't in the select, but the problem is that Count() is actually being called via the Grid, and handled externally from my code.

All I'm supposed to need to do is give the grid an IQueryable and it should be able to handle paging, sorting, etc. by itself.

Has anyone else had to get around this issue with NHibernate Fetching and how did you resolve it?

Teratism answered 9/3, 2011 at 19:47 Comment(0)
C
0
var query =  from s in repository.Query<MyClass>()
                     orderby s.Property.Name, s.Name
                     select s;
query = query.Fetch(x => x.Property).ToList();

and after you can go and do

query.Count() 

and it should be in working order.

As to why is that i suspect that is something to do

AsEnumerable()

or

AsQueryable()

but not sure why is this i had similar problem and this solved it...

Consignor answered 4/7, 2011 at 18:32 Comment(4)
The problem with that approach is that you'll bring back literally everything in that query. Later on the grid is actively paging that query so I only go to the database and get one page at a time. But the grid also needs a total count to handle the paging properly. This query in my question is the "base" query that the grid is working off of.Teratism
I have the same problem and this solution does not help as i have the same performance issue.Fairlead
@Joseph: how is set up your mapping? what about set eager loading in there?Consignor
@Consignor it's set up using Fluent NHibernates automapping and I'm using eager loading in my question, that's what the query.Fetch doesTeratism

© 2022 - 2024 — McMap. All rights reserved.