[英]EF Parent Child Inserts
I have the following database tables: Teachers
, Subjects
, and TeachersSubjects
. 我有以下数据库表:
Teachers
, Subjects
和TeachersSubjects
。
All the primary keys are setup properly. 所有主键均已正确设置。
I have a web page and would like to have a quick entry where I can just put in a teacher's name and a list of subjects she will be teaching. 我有一个网页,希望快速进入,我可以在其中输入老师的名字和她将要教的科目清单。
I am using VS2012 Express and Entity Framework. 我正在使用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();
So how do I go from my quick entry page to database in one click and propagate all three tables? 那么,如何一键从快速输入页面转到数据库并传播所有三个表?
Use this: 用这个:
// 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();
Or by your example: 或以您的示例为例:
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();
Use the following code: 使用以下代码:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.