user793468
user793468

Reputation: 4976

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

    }
}

Upvotes: 2

Views: 4122

Answers (1)

Olaf
Olaf

Reputation: 899

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

Upvotes: 5

Related Questions