linq 从 Id 中获取值

linq get value from Id

现在我从 sql 数据库中得到了这个:

CourseId:    CousreCode
1            0507       
4            0508
5            0509
6            0511
7            0512
8            0510
9            0515

所以在我单击数据单元格后,它会在文本框中显示 CourseId,但现在我想获取与 CourseId 配对的课程代码值

这是我想要的:

所以在我单击数据单元格后,它会在文本框中显示 CourseId 但由于 CourseCode 在另一个 table 中,我不知道如何将 CourseCode 值显示到文本框

这就是我遇到的问题

 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            using (AP2Context context = new AP2Context())
            {
                tbCourseId.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
                tbCourseCode.Text = ...
            }
        }

使用你的 Courses DbSet,你也许可以写:

tbCourseCode.Text = context.Courses.Find(...).CourseCode;

或(从数据库重新加载)

tbCourseCode.Text = context.Courses.First(c => c.CourseId == ...).CourseCode;

... 替换为具有正确类型的所选课程 CourseId:

  • 如果是字符串,请重用从为 tbCourseId.Text 编写的表达式中获得的值。
  • 如果是 int,则在必要时使用 int.Parse() 将其转换为 int