繁体   English   中英

实体框架:关系中不存在的 select 记录

[英]Entity Framework: select records that don't exist in relationship

我正在努力获取缺少必修课程的学生名单。

我有一个使用连接表的多对多关系:

学生:

public class Student: IBaseEntity
{
    [Key]
    public Guid ID { get; set; }

    private string _name = string.Empty;
    public string Name
    {
        get => _name;
        set => _name = value!.ToUpper(CultureInfo.InvariantCulture);
    }
    // removed additional fields for brevity
}

课程:

public class Course: IBaseEntity
{
    [Key]
    public Guid ID { get; set; }

    private string _name = string.Empty;
    public string Name
    {
        get => _name;
        set => _name = value!.ToUpper(CultureInfo.InvariantCulture);
    }

    public bool Required { get; set; }

    // removed additional fields for brevity
}

行动:

public class Action: IBaseEntity
{
    [Key]
    public Guid ID { get; set; }

    public Student Student { get; set; }

    public Course Course { get; set; }
    
    // the date that the student took the course
    public Datetime AttendedDate { get; set; }

    // removed additional fields for brevity
}

如何获取缺少必修课程的学生列表?

例如作为Dictionary<string, Student> ,其中 string 是课程和没有参加课程的学生。

我尝试了一个foreach(var s in Students)和一个foreach(var c in courses) ,但它挂起......

Dictionary<string, Student> dict = new();

foreach (var s in Students)
{
    foreach (var c in Courses)
    {
        bool exists = actions.Any(x => x.Student.ID.Equals(c.ID) && x.Course.ID.Equals(c.ID));

        if (!exists)
        {
            dict.Add(r.Name, c);
        }
    }
}

也许我以错误的方式处理关系?

任何帮助表示赞赏。

PS:对不起我的英语,不是我的母语。

您必须测试x.Student.ID.Equals(s.ID)而不是c.ID

而且您不能将重复的键添加到字典中。 例如,将s和缺少的c添加到List<(Student student, Course course)>中,其中列表包含元组。

List<(Student student, Course course)> missing = new();
foreach (var s in Students) {
    foreach (var c in Courses) {
        bool exists = actions.Any(a => a.Student.ID == s.ID && a.Course.ID == c.ID);
        if (!exists) {
            missing.Add((s, c));
        }
    }
}

foreach (var (student, course) in missing) {
    Console.WriteLine($"{student.Name} did not attend \"{course.Name}\"");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM