简体   繁体   中英

Entity Framework - Wrap collection of related objects

I'm trying to wrap a collection of related objects into a single object using Entity Framework. My situation is as follows: I have an entity called "Student" and an entity called "Book". The relationship between those is like this: "Student"-1-----*-"Book" . Obviously several books can belong to the same Student. Now I try to explain simplified what I'm trying to achieve: I want to access the Books property on Student like this: Student.Books but only the books published after 1990 should be contained in the collection. I think I would have to intercept the select statement of Entity Framework to achieve this, but I have no clue how to do this. Even better would be if the Books property is an instance of a custom wrapper class that contains the collection of Books so I can define methods to filter the collection directly on the Books property. Thank you for your help!

Regards sjkm

You could create a property in a partial for your Entity Framework Model Class object for Student like this :-

public partial class Student
{
   public IQueryable<Book> FilteredBooks
   {
      get
      {
         return this.Books.Any(b=> b.PublishedDate.Year >= 1990).AsQueryable();
      }
   }

}  

In theory, you should now be able to access :-

object.Datasource = Student.FilteredBooks.ToList();

Hope this helps?

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