locked
How to update both child and parent table in single transaction using entity framework? RRS feed

  • Question

  • Hi I have a code specified below, it is currently Inserting the new rows into child table and updating the parent table.

    var child= new Child();
    child.Parent= parent;
    DataContext.Parent.Add(parent); 
    DataContext.Entry(parent).State = EntityState.Modified;

    Now I want both the parent and child tables to be updated in a single transaction. It will be very helpful if any one could help me. Thanks in advance.

    Thursday, January 23, 2014 10:44 AM

Answers

  • Hello,

    >>Now I want both the parent and child tables to be updated in a single transaction

    In Entity Framework, there is two ways to update a record.

    First:

    1.We find the record which we want to update as below:

    var stud = (from s in ctx.Students
    
                            where s.StudentName == "Student1"
    
                            select s).FirstOrDefault();
    

    2.We modify the properties of the entity and call the SaveChange():

    stud.StudentName = "Updated Student1";
    
    int num = ctx.SaveChanges();
    

    Second:

    1.We create an new entity directly and attach it to context and change its state to be modified:

    Student stud=new Student(){SID=1,SName=”Name001” };
    
    ctx.Students.Attach(stud); 
    
    ctx.Entry<Student>( stud).State = EntityState.Modified;
    

    2.Then we call SaveChange() to save it to database.

    int num = ctx.SaveChanges();

    If you want update both parent and child tables, you can find these records in both parent and child tables and then modify them and then save them back to database as the first way. The second way need us to know the existing record in database first.

    For the single transaction, we just need to call the SaveChange() at last and it will just create one built-in transaction.

    For more information, please refer to link below:

    http://www.entityframeworktutorial.net/update-entity-in-entity-framework.aspx

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by Fred Bao Monday, February 3, 2014 8:51 AM
    Friday, January 24, 2014 3:24 AM