我有一个由以下模型表示的遗留类数据库。
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; }
}
我需要获取类(class)名称或描述的一部分或学生姓名的一部分与我的搜索字符串匹配的类(class)列表。第一部分很简单。
List<Course> courses = db.Courses.Where(w => w.Title.IndexOf(searchString) > -1 || w.Description.IndexOf(searchString) > -1).ToList();
我现在如何过滤 w.Attendees.Student.Name?
我试过:
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();
它只返回一个空列表。
我对 Linq 还是有点陌生,我来自 Grails。感谢您的帮助。
最佳答案
尝试只运行 w.Attendees.Any(a => a.Student.Name.IndexOf(searchString)
并调试它,因为 Attendees
可能为 null 或为空, Student
属性也是如此。
此外,如果您的数据库不区分大小写,您应该考虑更改代码以反射(reflect)这一点:
w.Attendees.Any(a => a.Student.Name.ToLowerInvariant().Contains(searchString.ToLowerInvariant())
区分大小写也可能是您问题的根源。
关于c# - Entity Framework 如何按导航属性的属性过滤我的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43348343/