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?

madaboutcode
  • 2,137
  • 1
  • 16
  • 23

2 Answers2

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);
themarcuz
  • 2,573
  • 6
  • 36
  • 53
Steve Strong
  • 271
  • 3
  • 6
  • 3
    Fetch must be placed after Where or you will get an exception. – Nicolas Cadilhac Dec 07 '10 at 18:36
  • @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 – leora Dec 30 '10 at 14:23
  • @Nicolas Cadilhac, @Steve Strong - When i run this, i get "notsupported Exception" – leora Dec 30 '10 at 14:52
  • @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. – Nicolas Cadilhac Jan 06 '11 at 15:14
-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
Community
  • 1
  • 1
Francis
  • 11