Get subset of entity navigation properties

前端 未结 1 1403
滥情空心
滥情空心 2021-01-23 00:39

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.Inc         


        
相关标签:
1条回答
  • 2021-01-23 01:00

    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.

    0 讨论(0)
提交回复
热议问题