简体   繁体   English

实体框架-包装相关对象的集合

[英]Entity Framework - Wrap collection of related objects

I'm trying to wrap a collection of related objects into a single object using Entity Framework. 我正在尝试使用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" . 它们之间的关系是这样的: "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. 现在,我尝试简化解释一下我要实现的目标:我想像这样访问Student上的Books属性:Student.Books,但是集合中只应包含1990年以后出版的书。 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. 我想我必须拦截Entity Framework的select语句才能实现此目的,但是我不知道如何执行此操作。 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. 更好的是,如果Books属性是一个自定义包装类的实例,该包装类包含Books的集合,那么我可以定义直接在Books属性上过滤该集合的方法。 Thank you for your help! 谢谢您的帮助!

Regards sjkm 问候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? 希望这可以帮助?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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