none
Can Entity Framework object (Context) use existing transaction? RRS feed

  • Question

  • Hello,

    As we know entity framework object context use transaction internally. But here I have method which insert different entity instance entry into db, for that i write method with new context.

    For e.g. : 

    public bool SavePatient(PatientInfo objPatientInfo) { using(var tr = new TransactionScope()) { using(var context = new HSEntity()) { //.... Save patient info. context.SaveChanges(); PatientBO.SavePatientInsurance(PatientInfo.Insurance) //Add or update patient insurance. context.SaveChanges(); tr.Commit(); } } } public bool SavePatientInsurance(InsuranceInfo info) { using(var context = new HSEntity()) { // Save insurance info context.SaveChanges(); } }

    Can i use existing transaction with newly created context.


    Than's In advanced.

    Monday, December 10, 2012 6:28 AM

All replies

  • Hi Vjyxyz,

    Welcome to the MSDN forum.

    I am not sure why you want to save an entity and its related entity separately. If you want to do this, you should detach the PatientInfo.Insurance and attach it in the context of SavePatientInsurance method.

    Have a nice day.


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, December 11, 2012 8:45 AM
  • Hello Alexander,

    Thank's for reply. As you told me detach teh patientInfo.Insurance and attach it in the context of SavePatientInsurance, but our structure is like that we have small small function to store entity object with new context but now we need transaction for that.

    I have one way to do this just I have to pass context as parameter and achieve the transaction. But I believe It is not good practice. So i need another way to do this. 

    If you can contribute more then it is helpful to me.

    Thank You

    Tuesday, December 11, 2012 2:00 PM
  • Hi Vjyxyz,

    Could you please let me know why you want to create a new context for using the function to store entity objects? 

    Normally, SaveChanges() saves the entity objects and its related entity objects automatically. Why do you want to do that manually?

    Best Regards,


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Sunday, December 16, 2012 7:11 AM
  • I have the same question as the OP. For us it is due to having a running transaction on a DbConnection that has simple SQL run against it, and the ObjectContext must not commit on its own, but as a part of the larger transaction. Any way of doing this?
    Friday, July 25, 2014 10:07 AM