0

How to insert data in trasaction using entity-framewrok-4?

I have a order object and it has other collection that i need to inset in database in transaction.

cOrder->
 ->lstOrderItems
   -->lstDressing, lstTopping, lstspecialInstruction
 ->userDetails
 ->trasactionTblsdetails

Also opinion required:- 1) Is it good to maintain transaction at database level or entity framework level. 2) What should be coding style.

right now i am following it this way but as i can predict it would require a lot of code but want to know this is only the way it work or far better solution exist.

public static void SaveOrder()
    {
        using (EposWebOrderEntities Ctx = new EposWebOrderEntities())
        {
            using (TransactionScope scope = new TransactionScope())
            {

                // do something...
                Ctx.order.SaveChanges();
                // do something...
                //foreach to save the order items to databaswe
                Ctx.orderitems.SaveChanges();
                // do something...
                //foreach to save in dressing tbl
                Ctx.dressing.SaveChanges();
                //foreach to save in topping tbl
                Ctx.topping.SaveChanges();
                //foreach to save in dressing tbl
                Ctx.dressing.SaveChanges();
                //foreach to save in spinst tbl
                Ctx.dressing.SaveChanges();
                scope.Complete();
                success = true;
            }
        }
    }
1
  • Tables do not have a SaveChanges method. I'm also unclear on what you're asking. Any concrete problem?
    – usr
    May 15, 2014 at 10:31

1 Answer 1

1

Use it this way. Is sufficient in most scenarios.

public static void SaveOrder()
    {
        using (EposWebOrderEntities Ctx = new EposWebOrderEntities())
        {
             Ctx.Entry<Order>(order).State = EntityState.Added;
             Ctx.Entry<Dressing>(dressing).State = EntityState.Added;
             Ctx.SaveChanges();

        }
    }

http://msdn.microsoft.com/en-us/library/dn456843.aspx

In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete >on the database the framework will wrap that operation in a transaction. This transaction lasts >only long enough to execute the operation and then completes. When you execute another such >operation a new transaction is started.

2
  • While true, this will not wrap anything else in a tran for example reads or multiple SaveChanges calls. Not very general.
    – usr
    May 15, 2014 at 10:51
  • for the collection in do not need to read each object with for-each and push to database..it will work.. May 15, 2014 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.