获取实体导航属性的子集子集、实体、属性

2023-09-04 01:21:45 作者:森屿海巷

我有用户实体与许多产品的实体,我需要一种方式来获得用户实体,其产品的子集,不是所有的产品。

I have User entity and related to many product entity , I need a way to get the user entity with subset of its products not all the products.

var user = User.Include("Product").ToList();  // it returnes all the products.

我需要一种方法来只有15产品回报用户。

I need a way to return the User with only 15 products.

在此先感谢...

推荐答案

您不能过滤或其中装入导航性能的其他方式的数据影响。当您使用预先加载或相关实体的延迟加载,那么EF少了点LEFT OUTER JOIN不附带任何条件。

You can't filter or affect in some other way data which are loaded into navigation properties. When you use eager loading or lazy loading of related entities, then EF just does LEFT OUTER JOIN without any conditions.

您可以返回匿名对象与用户及其15个产品:

You can return anonymous object with user and its 15 products:

var query = from u in db.Users
            select new {
                User = u,
                Top15Products = u.Products.Take(15)
            };

请注意 - 如果您装入用户实体,那么你可以装载相关实体的过滤系列:

NOTE - if you have user entity loaded then you can load filtered collection of related entities:

var user = db.Users.Find(1);

db.Entry(user)
  .Collection(u => u.Products)
  .Query()
  .Take(15)
  .Load();

此方法描述在加载相关实体的文章。