简体   繁体   中英

Entity Framework: Loading Filtered Collections

Given the next model

public class Author{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Book> Books { get; set; }

    public IQueryable<Book> GetGoodBooks(){
        return Books.Where(n => n.Rating > 6)
    }
}

public class Book{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Rating { get; set; }
    public Author Author { get; set;}
}

I need to retrieve ( in only one query ) all the authors with all their good books (using GetGoodBooks() ). So i do the next:

IQueryable<Author> query = from author in repository.ListAll<Author>() // it returns an IQueryable<Author>
                           select new Author() {
                               author.Id,
                               author.Name,
                               Books = author.GetGoodBooks() // it throws an exception
                           };

var list = query.ToList();

As you know, it will throw an exception because of using the method GetGoodBooks() within the Linq to Entities.

So, i know that i can make it works replacing the method for Linq clause like this:

IQueryable<Author> query = from author in repository.ListAll<Author>() // it returns an IQueryable<Author>
                           select new Author() {
                               author.Id,
                               author.Name,
                               Books = author.Books.Where(n => n.Rating > 6)
                           };

var list = query.ToList();

It works ok, but i want to use the author's interface i've designed!

Do you know any way i can do this maintaining the object design?

在LINQ to Entities中使用自定义方法/扩展方法的可能的双重解决方法当我开始使用EF时,我有相同的想法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM