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?

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Fetch must be placed after Where or you will get an exception.
@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 confused
@Nicolas Cadilhac, @Steve Strong - When i run this, i get "notsupported Exception"
@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.
-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

1 Comment

there is no QueryOptions in NHibernate 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.