Click here to Skip to main content
12,548,647 members (52,077 online)
Rate this:
Please Sign up or sign in to vote.
See more: C#
I was going through the examples of[^]

here in updating the one to many case my a new standard is added to my Standard table instead of updating the old one. Also in teachers table new teacher is added with standard id of the newly created standard. here is my code ...

Standard std = null;
using (SchoolDBEntities ent = new SchoolDBEntities())
    ent.ContextOptions.LazyLoadingEnabled = false;
    std = (from s in ent.Standards.Include("Teachers") where s.StandardName == "Standard2" select s).FirstOrDefault<Standard>();
std.StandardName = "UpdatedStandard";
std.Description = "Updated Class";
if (std.Teachers != null)
    if (std.Teachers.Count >= 2)
        Teacher updtTeacher = std.Teachers.ElementAt<Teacher>(0);

        Teacher delTeacher = std.Teachers.ElementAt<Teacher>(1);
        updtTeacher.TeacherName = "UpdatedTeacher";
Teacher newTeacher = new Teacher();
newTeacher.TeacherName = "NewTeacher";
using (SchoolDBEntities ent = new SchoolDBEntities())

    var existingStandard = (from s in ent.Standards where s.StandardId == std.StandardId select s).FirstOrDefault<Standard>();
    var existingTeachers = existingStandard.Teachers.ToList<Teacher>();
    var newTeachers = std.Teachers.ToList<Teacher>();
    var addedTeachers = newTeachers.Except(existingTeachers, tchr => tchr.TeacherId);
    var deletedTeachers = existingTeachers.Except(newTeachers, tchr => tchr.TeacherId);
    var updatedTeachers = existingTeachers.Except(deletedTeachers, tchr => tchr.TeacherId);
    //foreach(Teacher t in addedTeachers.ToList<Teacher>())
    //    ent.Teachers.AddObject(t);

    addedTeachers.ToList<Teacher>().ForEach(t => ent.Teachers.AddObject(t));

    foreach (Teacher t in updatedTeachers)
        ent.ObjectStateManager.ChangeObjectState(t, System.Data.EntityState.Modified);
    foreach (Teacher t in deletedTeachers)

somebody please help
Posted 3-Feb-13 2:55am
Edo Tzumer 3-Feb-13 9:10am
What seems to be the problem?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.161021.1 | Last Updated 3 Feb 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100