簡體   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