Get subset of entity navigation properties

不问归期 提交于 2019-12-20 02:52:19

问题


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.

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

Thanks in advance...


回答1:


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.

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();

This approach described at Loading Related Entities article.



来源:https://stackoverflow.com/questions/22504006/get-subset-of-entity-navigation-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!