【发布时间】:2020-07-03 06:07:17
【问题描述】:
ASP Core 与 MsSQL
我检查了很多类似问题的答案,但没有找到答案。
Student 表和 Course 表通过联结表 StudentCourse 连接:
Student StudentCourse Course
========= ============ =======
PK | ID FK | StudentID PK | ID
| Name FK | CourseID | Name
我想为决定更改课程的学生更新/更改联结 StudentCourse 表中的 CourseId。 我的上下文类:
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);
}
}
我的控制器的方法:
[HttpPost]
public IActionResult ChangeCourse(CourseModel newCourse)
{
// I want to get course Id for this student
Guid courseId = (from student in context.StudentModels
join cours in context.CourseModels on student.Id equals studentId
where cours.Id == oldCourseId
select cours.Id).SingleOrDefault();
// Change course Id
courseId = newCourse.Id;
context.SaveChanges();
return RedirectToAction();
}
根据Microsoft FAQ ,更新数据库中的一行需要三个步骤:
- 在数据库中查询要更新的行。
- 对生成的 LINQ to SQL 对象中的成员值进行所需的更改。
- 将更改提交到数据库。
所以我按照以下步骤操作:
- 在数据库中查询要更新的行。
Guid courseId = (from student in context.StudentModels
join cours in context.CourseModels on student.Id equals studentId
where cours.Id == oldCourseId
select cours.Id).SingleOrDefault();
- 对生成的 LINQ to SQL 对象中的成员值进行所需的更改。
oldCourseIdd = newCourse.Id;
- 将更改提交到数据库。
context.SaveChanges();
但它不会保存更改。我不明白为什么?
【问题讨论】:
-
提交??????????
-
这是什么:
oldCourseIdd? -
这里只是迂腐。 LINQ中的Q代表query,没有U代表update。通常我们不使用 LINQ 来更新我们使用它来查询的东西
</PedanticismOver> -
“对生成的 LINQ to SQL 对象中的成员值进行所需的更改。”您发布的代码只是不这样做。
oldCourseIdd来自哪里?这是“生成的 LINQ to SQL 对象”吗? -
这真的是 LINQ to SQL 吗?在我看来更像实体框架; LINQ to SQL 与 EF 完全不同,仅适用于 SQL 服务器,而您已标记 mysql。通过阅读该常见问题解答,我感觉您正在遵循错误的教程;该代码适用于查询,因为 EF 使用 LINQ,但它不是 LtS,所以如果您使用 EF,请不要遵循 LtS 教程
标签: c# mysql linq asp.net-core entity-framework-core