Filter the “Includes” table on Entity Framework query

前端 未结 1 1596
说谎
说谎 2020-12-29 06:56

This is for Entity Framework for .NET 3.5:

I have the need to query a table and include a collection of the \"many\" table of a one-to-many relationship. I\'m tryin

相关标签:
1条回答
  • 2020-12-29 07:34

    The forward way:

    var q = from a in db.Authors.Include("Books")
            where a.BirthYear > 1900
            select new {
                Author = a,
                FictionBooks = a.Books.Where(b => b.IsFiction)
            };
    

    Another way, derived from the SQL at the bottom of your question:

    var q = from a in db.Authors
            from b in db.Books.Include("Author")
            where a.BirthYear > 1900 && b.IsFiction && a.Id == b.Author.Id
            select new { Author = a, Book = b };
    

    The main difference between these two is that the first one will basically give you a collection of authors plus the list of fiction books for each author (which may be empty); while the second will give you a collection of author/books pairs (so it doesn’t return any authors with no fiction books).

    0 讨论(0)
提交回复
热议问题