Eager load while using Linq in NHibernate 3
Asked Answered
S

2

8

I need help with eager loading in with Linq in NHibernate 3 trunk version.

I have a many-to-many relationship like this:

public class Post
{
    public int Id {get;set;}
    public IList<Tag> Tags { get;set;} 
    .
    .
    .
}

Now I have the following mapping in Fluent NHibernate

public class PostMap:ClassMap<Post>
{
    public PostMap()
    {
        Table("Posts");
        Id(x => x.Id);
        .
        .
        HasManyToMany(x => x.Tags)
            .Table("PostsTags")
            .ParentKeyColumn("PostId")
            .ChildKeyColumn("TagId")
            .Not.LazyLoad(); // this is not working.. 
    }
}

Now while fetching the posts, I need the Tags also to eager load. I know that it is possible with Criteria API and HQL and the SetFetchMode is what I should use. But is there are way to use SetFetchMode when using Linq?

Smithsonite answered 15/1, 2010 at 21:57 Comment(0)
V
13

Support for this went into the trunk sometime ago; the syntax is be something like

var query = session.Query<Post>().Where(bla bla).Fetch(p => p.Tags);

If Tags in turn had another relationship, you can do:

var query = session.Query<Post>().Where(bla bla).Fetch(p => p.Tags).ThenFetch(t => t.SomethingElse);
Valvate answered 2/7, 2010 at 10:6 Comment(4)
Fetch must be placed after Where or you will get an exception.Burford
@Nicolas Cadilhac, @Steve Strong - how do you add a where after a ThenFetch ?? Nicolas response says the above doesn't work but its the accepted answer so i am confusedIslet
@Nicolas Cadilhac, @Steve Strong - When i run this, i get "notsupported Exception"Islet
@ooo: as you and I mentioned, Fetch and ThenFetch must be the last clause. I accepted the answer knowing that I added a comment to tell about this constraint. In another SO question, I tried to know if there is a workaround (I need some Where clause after a fetch and paged result) but it seems the current status of LinqToNH does not allow it. So to answer your question, you can do it only with HQL or Criteria API. Also I don't know why Linq does not honnor the lazy statement set in the mapping.Burford
G
-2

For me this thread solve problem.

Linq for NHibernate - filtering on <many-to-one> foreign key causes extra lookup

var linqsession = session.Linq<FeedItem>();
linqsession.QueryOptions.RegisterCustomAction(c => c.SetResultTransformer(new DistinctRootEntityResultTransformer()));
var feedItemQuery = from ad in linqsession.Expand("Ads")
                    where ad.Id == Id
                    select ad
Gutturalize answered 4/7, 2010 at 18:7 Comment(1)
there is no QueryOptions in NHibernate 3Protactinium

© 2022 - 2024 — McMap. All rights reserved.