多对多关系过滤/搜索

时间:2018-12-07 12:55:33

标签: c# asp.net-core entity-framework-core

你好,我想过滤到LanguageSchool表,但是LanguageSchool表与LanguageSchoolProgram表有关系(很多)。

public class LanguageSchool
{
    public virtual List<LanguageSchoolLanguageSchoolProgram> LanguageSchoolLanguageSchoolPrograms { get; set; }
}

public class LanguageSchoolProgram
{
     public long Id { get; set; }
     public virtual List<LanguageSchoolLanguageSchoolProgram> LanguageSchoolLanguageSchoolPrograms { get; set; }
}
public class LanguageSchoolLanguageSchoolProgram
{
    public long LanguageSchoolProgramId { get; set; }
    public virtual LanguageSchoolProgram LanguageSchoolProgram { get; set; }
    public long LanguageSchoolId { get; set; }
    public virtual LanguageSchool LanguageSchool { get; set; }
}

我有X语言学校课程,Y语言学校课程和Z语言课程以及很多语言学校。

我想选择语言学校,但语言学校包含X和Y程序。

并且我必须使用.AsQueryable()函数。

1 个答案:

答案 0 :(得分:0)

您的问题不清楚...我不确定您如何存储程序X,Y,Z?我假设这些是程序名称。

您可以这样定义您的多对多关系:

public class LanguageSchool
{
    public int LanguageSchoolId { get; set; }
    public virtual ICollection<LanguageSchoolProgram> LanguageSchoolPrograms { get; set; }
}

public class LanguageSchoolProgram
{
    public int LanguageSchoolProgramId { get; set; }
    public string ProgramName {get; set;} // this is X, Y or Z
    public virtual ICollection<LanguageSchool> LanguageSchools { get; set; }
}

并使用Contains选择列表中有课程的学校:

string[] requiredPrograms = new string[] {"X", "Y", "X"};
var schoolsQueryable = dbContext.LanguageSchool.Where(
    ls => requiredPrograms.contains(ls.LanguageSchoolProgram.ProgramName));

// if you don't want Queryable, then add ToList()