Click here to Skip to main content
15,884,628 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I was going through the examples of http://entityframeworktutorial.net/[^]

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 ...

C#
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);

        std.Teachers.Remove(delTeacher);
        std.Teachers.Remove(updtTeacher);

        updtTeacher.TeacherName = "UpdatedTeacher";
        std.Teachers.Add(updtTeacher);
    }
}
Teacher newTeacher = new Teacher();
newTeacher.TeacherName = "NewTeacher";
std.Teachers.Add(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.Teachers.Attach(t);
        ent.ObjectStateManager.ChangeObjectState(t, System.Data.EntityState.Modified);

    }

    foreach (Teacher t in deletedTeachers)
    {
        ent.Teachers.DeleteObject(t);

    }

    ent.SaveChanges();

}



somebody please help
Posted
Comments
Joezer BH 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900