c# - Entity Framework 如何按导航属性的属性过滤我的结果?

标签 c# entity-framework linq

我有一个由以下模型表示的遗留类数据库。

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/

相关文章:

c# - Merge 2排序时间序列算法

c# - 在 C# 中使用定长数组

c# - 实体类型 'IdentityUserLogin<string>' 需要定义主键

entity-framework - 使用 DateTime 和 TimeSpan net core 2.0 和 EF 的算术值

c# - XML根据时间戳删除节点C#

c# - 使用linq写入xml文件

c# - Linq EF Include() with Select() new type lost included

c# - 具有区域的 ASP.NET Core 2 默认路由

c# - 在 DataGridView 中显示导航属性的属性(二级属性)

c# - LINQ 是将 SQL Server 中的所有项目加载到内存中还是仅加载到 block 中?