EF父子插入

时间:2013-08-03 04:11:18

标签: c# entity-framework

我有以下数据库表:TeachersSubjectsTeachersSubjects

所有主键都已正确设置。

我有一个网页,想要快速输入,我可以在其中输入教师的名字和她将要教授的科目列表。

我正在使用VS2012 Express和Entity Framework。

    NorthwindCustEntities context = new NorthwindCustEntities();

    Teacher t1 = new Teacher() { Name = "Jane Smith" };

    Subject s1 = new Subject() { Name = "Math" };
    Subject s2 = new Subject() { Name = "Science" };

    context.Subjects.Add(s1);
    context.Subjects.Add(s2);
    context.Teachers.Add(t1);

    context.SaveChanges();

那么如何通过一次点击从快速输入页面转到数据库并传播所有三个表?

2 个答案:

答案 0 :(得分:1)

使用此:

// think we have a 
string teacherName;
// and a list of 
string[] subjectNames;
// then:

NorthwindCustEntities context = new NorthwindCustEntities();

Teacher t1 = new Teacher() { Name = teacherName };
t1.Subjects = new List<Subject>();
foreach(var subject in subjectNames) {
    t1.Subjects.Add(new Subject() { Name = subject });
}

context.Teachers.Add(t1);

context.SaveChanges();

或者通过你的例子:

NorthwindCustEntities context = new NorthwindCustEntities();

Teacher t1 = new Teacher() { Name = "Jane Smith" };

Subject s1 = new Subject() { Name = "Math" };
Subject s2 = new Subject() { Name = "Science" };

t1.Subjects.Add(s1);
t1.Subjects.Add(s2);
context.Teachers.Add(t1);

context.SaveChanges();

答案 1 :(得分:1)

使用以下代码:

NorthwindCustEntities context = new NorthwindCustEntities();

Teacher t1 = new Teacher() { Name = "Jane Smith" };

Subject s1 = new Subject() { Name = "Math" };
Subject s2 = new Subject() { Name = "Science" };

context.Subjects.Add(s1);
context.Subjects.Add(s2);

t1.Subjects.Add(s1);
t1.Subjects.Add(s2);
context.Teachers.Add(t1);

context.SaveChanges();