0

This should be straightforward but I'm not making any progress on this issue. I want to write a LINQ statement that returns a person matching a given ID and include a set of visits. That I can do. Now, I need to include only active visits, that is include the visit only if the IsActive flag is true. My query is included below. What am I doing wrong?

var inmate = this.db.Inmates.Where(p => p.Id == id).Include(p => p.Visits.Where(v => v.IsActive)).FirstOrDefault();

Update #1 - I also tried this statement:

var inmate = this.db.Inmates.Include(p => p.Visits).Where(p => p.Id == id && p.Visits.Any(v => v.IsActive)).FirstOrDefault();
user1469655
  • 1,031
  • 1
  • 12
  • 18
  • Have you seen this SO question http://stackoverflow.com/questions/1680863/linq-include-with-where-clause? – Dan Carlstedt Jun 25 '12 at 02:51
  • 1
    I believe you are trying to do a conditional eager loading where by when you access inmateObject.Visits you only want the list of Active visits. This is already discussed over here; http://stackoverflow.com/questions/3718400/conditional-eager-loading – Prashanth Thurairatnam Jun 25 '12 at 03:04
  • @prashantht I agree. I really don't think there is any way to do this other than how they suggested in your link. – Dan Carlstedt Jun 25 '12 at 03:06

1 Answers1

0

Try this:

var inmate = this.db.Inmates.Where(i => i.Visits.Any(x => x.IsActive))

Note: that the code assumes that the IEnumerable<Visits> is a property of an Inmate object.

Kane
  • 16,471
  • 11
  • 61
  • 86