如何将多个模型保存到Db Context(EF)

时间:2015-11-20 05:28:34

标签: asp.net-mvc entity-framework

我坚持在Db Context上保存我的模型,我不知道从哪里开始或我将如何继续。

我有3个型号(这是一个易于阅读的条形版本)

public class Student
{
    [Required]
    public int Id { get; set; }
    public virtual List<SyTerm> SyTerm { get; set; }
}

public class SyTerm
{
    [Required]
    public int Id { get; set; }
    public virtual List<Course> Courses { get; set; }
}
public class Course
{
    [Required]
    public int Id { get; set; }
}

我的问题是当我尝试使用Entity Framework

保存它时
        db.Courses.Add(cortemp1);
        db.Courses.Add(cortemp2);

        db.Students.Add(stud);
        ...
        db.SaveChanges();

我总是收到错误(各种错误,如冲突等) 我不确定如何保存它的正确顺序。

例如我有这个

    var stud = new Student();
    var sys = new List<SyTerm>();
    var cours = new List<Course>();

    var sytemp1 = new SyTerm();
    var sytemp2 = new SyTerm();

    var cortemp1 = new Course();
    var cortemp2 = new Course();

如何对其进行排序以将其保存在我的Db中?

3 个答案:

答案 0 :(得分:1)

首先,如果您以正确的方式拥有实体关系,则不需要进行多次保存更改,因此请执行此类操作

var stud = new Student();
var sys = new List<SyTerm>();
var cours = new List<Course>();



var sytemp1 = new SyTerm();
var sytemp2 = new SyTerm();

sys.Add(sytemp1);//add data to collection
var cortemp1 = new Course();
var cortemp2 = new Course();


  stud.SysTerm = sys;// here we are saying that student entity has this collection

 dbCtx.Student.add(stud); // just add student
 dbCtx.SaveChanges()

简单来说,将所有对象添加到学生然后只需添加它并保存更改,因为学生现在是一个完整的实体。如需精确样品,请查看 http://www.entityframeworktutorial.net/code-first/simple-code-first-example.aspx

答案 1 :(得分:0)

我认为你应该在Course和SyTerm之间建立关系,所以你的课程应该是这样的:

public class Course
{
   [Required]
   public int Id { get; set; }
   public virtual SyTerm { get; set; }
}

当然,如果需要,你必须初始化它

答案 2 :(得分:0)

添加/更新实体框架实体时,必须确保考虑数据库外键关系并正确映射它。在你的情况下,SysTerm有课程列表,但当然也应该有一个SysTerm Id属性,以确保维护正确的一对多关系。示例如下所示如何以正确的方式创建实体关系

public class Student
{
    public Student()
    { 

    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }

    //Foreign key for Standard
    public int StandardRefId { get; set; }

    [ForeignKey("StandardRefId")]
    public Standard Standard { get; set; }
}

public class Standard
{
    public Standard()
    { 

    }
    public int StandardId { get; set; }
    public string StandardName { get; set; }

    public ICollection<Student> Students { get; set; }

 }

请查看此答案以获取更多详细信息:Understanding ForeignKey attribute in entity framework code first

相关问题