1

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

Whistler
  • 1,897
  • 4
  • 29
  • 50
  • What error are you getting? – Sami Jan 23 '16 at 12:21
  • Error message: "The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path" – Whistler Jan 23 '16 at 12:25
  • Would this help: http://stackoverflow.com/a/16801205/3279876 – Sami Jan 23 '16 at 12:42
  • No as I don't want to create new model/object, I just want to reduce number of results – Whistler Jan 23 '16 at 12:52
  • Try Include(u => u.JobTitles).Where(e => e.Language == strLang).ToList(); – Sami Jan 23 '16 at 12:56
  • No, unfortunately it doesn't work: "'User' does not contain definition for Language. – Whistler Jan 23 '16 at 13:00
  • Is JobTitles a navigation property of Users? Can we see the Users and JobTitle classes? – Kirsten Jan 23 '16 at 16:08

2 Answers2

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);
}
Alexander Derck
  • 13,818
  • 5
  • 54
  • 76
1

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.

Jonathan Magnan
  • 10,874
  • 2
  • 38
  • 60