Selective eager loading in Entity Framework
Is it possible to limit the number of开发者_StackOverflow 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.
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: LINQ to Entities (Entity Framework) Join and .Include conflict
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.
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.
精彩评论