Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 更新代码优先现有数据库中实体框架中多对多关系中的数据_C#_Asp.net Mvc_Linq_Entity Framework - Fatal编程技术网

C# 更新代码优先现有数据库中实体框架中多对多关系中的数据

C# 更新代码优先现有数据库中实体框架中多对多关系中的数据,c#,asp.net-mvc,linq,entity-framework,C#,Asp.net Mvc,Linq,Entity Framework,我正在开发一个应用程序,努力理解如何在有中间联接表的表中更新数据(即打破多对多关系的表)。例如,从下面的图表。如果我说我想为新来的学生增加记录,包括三门课程,即数学、英语和计算机。我是怎么做到的 public virtual ICollection<StudentCourse> StudentCourses { get; set; } 我的第三个问题是,我是否必须在上述代码中使用虚拟关键字。首先,若您在学生课程(注册的这一学期)中并没有附加字段,那个么您就不需要上学生课程 如果要

我正在开发一个应用程序,努力理解如何在有中间联接表的表中更新数据(即打破多对多关系的表)。例如,从下面的图表。如果我说我想为新来的学生增加记录,包括三门课程,即数学、英语和计算机。我是怎么做到的

public virtual ICollection<StudentCourse> StudentCourses { get; set; } 

我的第三个问题是,我是否必须在上述代码中使用虚拟关键字。

首先,若您在
学生课程
(注册的这一学期)中并没有附加字段,那个么您就不需要上
学生课程

如果要保持此模式,可以执行以下操作:

StudentCourse registration = new  StudentCourse();
registration.StudentID = 4;
registration.CourseID = 6;
context.StudentCourses.Add(registration);
context.SaveChanges();
这些资源可能会为您提供进一步的解释:

如果要检查是否没有重复项,可以执行以下操作:

 if(context.Courses.Where(c => c.Title == 'Math').FirstOrDefault() == null)
 {
     //add the course
 }else {
     //already existing
 }

这很好!我有另一个关于你提供的链接上面的问题。。。不使用fluent api我能做到这一点吗?@为什么不使用fluent api?对于这项任务来说,它不是很复杂,也很有用?@是的,数据注释对于这项任务来说应该足够了,而且您确实不需要
StudentCourse
,如果有帮助,也不要忘记将其标记为正确答案:)
public partial class StudentCourse
{
    public int StudentCourseID { get; set; }
    public int StudentID { get; set; }
    public int CourseID { get; set; }

    public virtual Course Course { get; set; }
    public virtual Student Student { get; set; }
}
StudentCourse registration = new  StudentCourse();
registration.StudentID = 4;
registration.CourseID = 6;
context.StudentCourses.Add(registration);
context.SaveChanges();
 if(context.Courses.Where(c => c.Title == 'Math').FirstOrDefault() == null)
 {
     //add the course
 }else {
     //already existing
 }