如何使用EF6更新相关实体

时间:2018-11-03 02:35:15

标签: c# asp.net asp.net-mvc entity-framework entity-framework-6

我的数据库中有一些学生的课程记录。

Course Table 
Id | Name

Student Table
Id | Name | CourseId

例如,我可以开设“ 1(数学)”课程,其中包含5位学生,“安迪,卡尔,鲍勃,玛丽,哈里”

在我的模型中,我有这个:

public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<Student> Student { get; set; }
}

当我用学生列表保存新课程时,我使用此代码,并且一切正常。该课程将保存在DB中,并与他一起创建所有学生。

public TEntity Add(TEntity entity)
{
    this.context.Configuration.AutoDetectChangesEnabled = false;
    this.context.Configuration.ValidateOnSaveEnabled = false;
    this.EntitySet.Add(entity);
    this.context.SaveChanges();
}

但是,当我需要修改学生列表时,可以从代码中对其进行修改,但是在DB中,新关系不会更新。我使用此代码进行更新:

public TEntity Edit(TEntity entity)
{
    this.context.Configuration.AutoDetectChangesEnabled = false;
    this.context.Configuration.ValidateOnSaveEnabled = false;

    this.EntitySet.Attach(entity);
    this.context.Entry(entity).State = EntityState.Modified;
    this.context.SaveChanges();
}

所以,我的问题是:

当我更改课程列表时,如何使用实体框架更新来更新DB中的学生列表。

非常感谢

编辑1

这是一个例子。

// Params (Id, Name, Students)
Course maths = new Course(1, "Maths", "Andy, Carl, Bob, Mary, Harry");

this.Add(maths);
//In DB is created the Course and the students with DB relation. No problem.

maths.Students = new List<Student>();
maths.Students.Add("Igor");
maths.Students.Add("Carl");
maths.Students.Add("Sam");
maths.Students.Add("Dante");

this.Edit(maths);
//In DB is updated the maths Course register, but the Student's list is not updated.

0 个答案:

没有答案
相关问题