EF. How to include only some sub results in a model?

邮差的信 提交于 2020-01-21 21:01:06

问题


I'm trying to select list of Users and for each User JobTitle in correct language depended of strLang selected by user.

Something like that:

IList<User> myData;
myData = Context.Users.Where(u => u.Location == strLocation)
                .Include(u => u.JobTitles.Where(e => e.Language == strLang))
                    .ToList();

But it seems Include doesn't like Where clause


回答1:


You can't conditionally include only a few entities of a related collection, so you should use projection to get the stuff you need:

IList<User> myData;
var temp = Context.Users.Where(u => u.Location == strLocation)
      .Select(u => new
      {
        User = u;
        Locations = u.JobTitles.Where(e => e.Language == strLang));
      });

foreach(var t in temp)
{
   User user = t.User;
   user.Locations = t.Locations;
   myData.Add(user);
}



回答2:


You cannot do it by using the "Include" method since it only take naviation properties.

Disclaimer: I'm the owner of the project EF+ on github.

EF+ Query IncludeFilter allow you to easily filter related entities:

// using Z.EntityFramework.Plus; // Don't forget to include this.    
IList<User> myData;
    myData = Context.Users.Where(u => u.Location == strLocation)
                    .IncludeFilter(u => u.JobTitles.Where(e => e.Language == strLang))
                        .ToList();

You can find the project here

You can find the documentation here

Behind the code, IncludeFilter do exactly like Alexander answer by using a projection.



来源:https://stackoverflow.com/questions/34963319/ef-how-to-include-only-some-sub-results-in-a-model

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