Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving data in multiple tables in one transaction using entity framework

How can I save data into multiple tables in one transaction using entity framework?

I have multiple void methods where I populate the context, but I want to save it in one transaction rather than saving it multiple times. What is the best way of doing this?

namespace DataAccess.Services
{
    public class Submissions
    {
        DataContext Context;

        public Submissions()
        {
            Context = new DataContext();
        }

        public void InsertAllData()
        {
             //Save all data at once for all below contexts
             //DataContext.SaveChanges();  
        }

        void InsertObject1(int Object1Id )
        {
               var obj1 = new DataAccess.Entity.Object1();

                obj1.Field1 = ....
                obj1.Field2 = ....
                .....

                DataContext.Objects.Add(obj1);
        }

        void InsertObject2(int Object2Id )
        {
               var obj2 = new DataAccess.Entity.Object2();

                obj2.Field1 = ....
                obj2.Field2 = ....
                .....

                DataContext.Objects.Add(obj2);
        }

        void InsertObject3(int Object3Id )
        {
               var obj3 = new DataAccess.Entity.Object3();

                obj3.Field1 = ....
                obj3.Field2 = ....
                .....

                DataContext.Objects.Add(obj3);
        }

    }
}
like image 937
user793468 Avatar asked Apr 16 '26 15:04

user793468


1 Answers

Your example code looks fine.
Entity framework is a change tracker and keeps track of all your changes. Every change you make to an object in your context will be stored by that context locally and all changes will be commited at once when you call DataContext.SaveChanges();.
So in this case, if you subsequentially call your InsertObject1, then InsertObject2 and InsertObject3, and then DataContext.SaveChanges();, everything will be stored in one go.

If you meant how you can do all this in inside an SQL database transaction, you can read about how to use those here: http://msdn.microsoft.com/en-us/data/dn456843

like image 151
Olaf Avatar answered Apr 19 '26 09:04

Olaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!