ASP.Net Core vs MySQL
Student table and Course table are joined with the junction table StudentCourse:
Student StudentCourse Course
========= ============ =======
PK | ID FK | StudentID PK | ID
| Name FK | CourseID | Name
A student changes his course so manager needs to change CourseID in the junction table StudentCourse.
But I don't have direct access to the junction table due to:
public class AppDbContext
{
public DbSet<CourseModel> CourseModels { get; set; }
public DbSet<StudentModel> StudentModels { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<StudentCourse>()
.HasKey(t => new { t.StudentId, t.CourseId });
builder.Entity<StudentCourse>()
.HasOne(sc => sc.Student)
.WithMany(s => s.StudentCourse)
.HasForeignKey(sc => sc.StudentId);
builder.Entity<StudentCourse>()
.HasOne(sc => sc.Course)
.WithMany(s => s.StudentCourse)
.HasForeignKey(sc => sc.CourseId);
}
}
So I can't execute this SQL command directly:
UPDATE StudentCourse SET CourseId = '9A414E30-DA37-48ED-105E-08D8129A967A' WHERE StudentId = 'A1F38C12-AE65-464C-C489-08D814F4CDDC'
I think I have to use Inner Join. My logic is:
[HttpGet]
public IActionResult ChangeCourse(Guid id)
{
IQueryable<CourseModel> courses = courseModel.GetCourses();
ViewBag.Courses = new SelectList(courses, "Id", "Name");
var course = courseModel.GetCourseById(id);
return View(course);
}
[HttpPost]
public IActionResult ChangeCourse(CourseModel newCourse)
{
// I know student's id, so I can get his old course id
Guid oldCourseId = (from ... in ...).SingleOrDefault();
// Then just change and save
oldCourseId = newCourse.Id;
context.SaveChanges();
return RedirectToAction();
}
I have the SQL command to get an old course id:
SELECT CourseId FROM StudentModels L
INNER JOIN StudentCourse R
ON L.Id = R.StudentId
WHERE L.Id = 'A1F38C12-AE65-464C-C489-08D814F4CDDC'
So the questions are:
- Are my assumptions correct?
- How to write this SQL command in LINQ?
I tried this but got the list of Ids:
from student in context.StudentModels join cours in context.CourseModels on student.Id equals studentId select cours.Id
I'm not good at LINQ, yet. Please help.