Entity Framework How can I filter my results using a navigation property?
I have a legacy class database which is represented by the following model.
public class Course
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public CourseLevel Level { get; set; }
public float FullPrice { get; set; }
public Author Author { get; set; }
public IList<Tag> Tags { get; set; }
public IList<Attendee> Attendees { get; set; }
}
public class Attendee
{
public int Id { get; set; }
public int StudentId { get; set; }
public decimal Tuition { get; set; }
public Student Student { get; set; }
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Course> Courses { get; set; }
}
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Course> Courses { get; set; }
}
I need to get a list of classes that either part of the course name or description or part of the student name matches my search string. The first part is simple.
List<Course> courses = db.Courses.Where(w => w.Title.IndexOf(searchString) > -1 || w.Description.IndexOf(searchString) > -1).ToList();
How do I filter against w.Attendees.Student.Name now?
I tried:
List<Course> courses = db.Courses
.Where(w => w.Title.IndexOf(searchString) > -1 ||
w.Description.IndexOf(searchString) > -1 ||
w.Attendees.Any(a => a.Student.Name.IndexOf(searchString) > -1)).ToList();
And it just returns an empty list.
I'm still new to Linq, I am originally from Grails. Any help is appreciated.
Try to run only w.Attendees.Any(a => a.Student.Name.IndexOf(searchString)
and debug it because it Attendees
can be empty or empty and the same is true for the property Student
.
Also, in case your database is not case sensitive, you should consider changing your code to reflect this:
w.Attendees.Any(a => a.Student.Name.ToLowerInvariant().Contains(searchString.ToLowerInvariant())
Case sensitivity can be the source of your problems.
source to share