views:

71

answers:

3

Hello,

Is it possible to limit the number of associated entities eagerly loaded with Include?

e.g. I have Author and Book entities with a many-to-one relation I'd like to load all authors and their last book

Thanks.

A: 

Yes you can. You are going to do it through two queries.

First select your authors.

    List<Authors> authors =  context.Authors.ToList();

Second select your books.

    List<Books> books=
                   (   from b in context.Books
                          group b by b.AuthorName into groupedByAuthor
                           let maxDate = groupedByAuthor.Max(c=>c.PublishDate)
                          ...
                    ).ToList

When you do this EF will populate your book for the author. Note your reference will not be "loaded" but your 1 book will be there.

Try it... the joyous magic of EF.

Nix
A: 

I'd do it like this:

var list = (from a in Authors.Include("Books") 
           join b in books.OrderByDesc(b => b.PublishedDate).Take(1)
               on a.Id equals b.AuthorId into bo
           select new { Author = a, Books = b }).ToList();

List<Author> authors = list.Select(o => o.Author);

where Author is your entity name and Books in your Navigation Property in Author. you'll still have an EntityCollection for Books but it should only contain 1 element.

moi_meme
I don't believe the .Include("Books") is necessary here. Any conditional criteria (such as a Take or even the join it's self) tells EF that there is some conditions there and it should not include everything so the .Include is dropped. At least that's how I understand it and I've played with that syntax quite a lot.
Nate Zaugg
+1  A: 

You can't do it using the .Include syntax but you can do it using projection.

var list = (from a in data.Authors 
           select new 
           { 
              Author = a, 
              Books = (from b in a.Books select b).Take(1)
           }).ToList();

When you get the result the materializer will have used it's relationship fixup and you will be able to use list.Author.Books.

see my question at: http://stackoverflow.com/questions/2419984/linq-to-entities-entity-framework-join-and-include-conflict

Nate Zaugg