简体   繁体   中英

EF Parent Child Inserts

I have the following database tables: Teachers , Subjects , and 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM