locked
Entity Framework ObjectContext Best Pratice RRS feed

  • Question

  • I'm looking for the best code pratice. I'm using this on a WCF Service.

    I've two diferents implementation

    First implementation:











     




    public void UpdateEntity(Entity enity) { using (TransactionScope tx = new TransactionScope()) { DeleteEntityA(enity); UpdateEntityB(enity); UpdateEntityA(enity); tx.Complete(); } } private void UpdateEntityA(Entity enity) { using (ProductionEntitiesCnn ctx = new ProductionEntitiesCnn()) { // do something ctx.SaveChanges(); } } private void UpdateEntityB(Entity enity) { using (ProductionEntitiesCnn ctx = new ProductionEntitiesCnn()) { // do something ctx.SaveChanges(); } } private void DeleteEntityA(Entity enity) { using (ProductionEntitiesCnn ctx = new ProductionEntitiesCnn()) { // do something ctx.SaveChanges(); }


    }


    Second implementation:










    public void UpdateEntity(Entity enity) { using (TransactionScope tx = new TransactionScope()) { using (ProductionEntitiesCnn ctx = new ProductionEntitiesCnn()) { DeleteEntityA(ctx, enity); UpdateEntityB(ctx, enity); UpdateEntityA(ctx, enity); ctx.SaveChanges(); } tx.Complete(); } } private void UpdateEntityA(ProductionEntitiesCnn ctx, Entity enity) { // do something } private void UpdateEntityB(ProductionEntitiesCnn ctx, Entity enity) { // do something } private void DeleteEntityA(ProductionEntitiesCnn ctx, Entity enity) { // do something
    }

    I would like to have some opinions about the best code implementation?

    Regards,

    Rui Figueiredo.




    Wednesday, December 23, 2009 11:53 AM

Answers

  • Hi,
    Since you want to accomplish a transaction you should use the second approach.
    Creating a context for each operation which is included in a transaction is not recommended.

    I hope it will help you.
    Gil Fink
    Wednesday, December 23, 2009 6:30 PM