1

我有以下数据库表:TeachersSubjectsTeachersSubjects

所有主键均已正确设置。

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

我正在使用 VS2012 Express 和实体框架。

    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();

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

4

2 回答 2

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();
于 2013-08-03T04:17:25.953 回答
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();
于 2013-08-03T04:19:42.053 回答