Question

I use EF almost one year ago. I just try to use TransactionScope deal with quite complex query like the following code.

using (var tran = new TransactionScope())
{
    // Clear all data in some table
    DataContext.SomeTables
        .ForEach(x => DataContext.SomeTables.DeleteObject(x));

    DataContext.SaveChanges();

    // Import data from excel as DataSet object.
    var ds = ImportDataFromExcel(file.FullName);

    foreach (DataRow dr in ds.Tables[0].Rows)
    {
        DataContext.SomeTables.AddObject(new SomeTable
        {
            // fill object with data from current row.
        });
    }

    DataContext.SaveChanges();

    // Commit Transaction
    tran.Complete();
}

After that, I got some error about DTM is not enabled or accessible. I know it cause by this service at database server is not start or blocked by firewall. But it is not my point.

I want to know why EF uses this service to create transaction while plain SQL script can use only some statement like "BEGIN TRAN", "SAVE TRAN" or "ROLLBACK TRAN" does that.

Is there any other way to avoid calling DTM service for my quite simple transaction statement?

PS. Current working database is so small and I think it should not be affect from different transaction technic.

Thanks,

Was it helpful?

Solution

After I search a lot of websites, I just found I can manually create transaction using Entity transaction like the following source code.

using (var tran = DataContext.BeginTransaction())
{
    // Clear all data in some table
    DataContext.SomeTables
        .ForEach(x => DataContext.SomeTables.DeleteObject(x));

    DataContext.SaveChanges();

    // Import data from excel as DataSet object.
    var ds = ImportDataFromExcel(file.FullName);

    foreach (DataRow dr in ds.Tables[0].Rows)
    {
        DataContext.SomeTables.AddObject(new SomeTable
        {
            // fill object with data from current row.
        });
    }

    DataContext.SaveChanges();

    // Commit Transaction
    tran.Commit();
}

Helper class

public static DbTransaction BeginTransaction(this ObjectContext context, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
{
    if (context.Connection.State != ConnectionState.Open)
    {
        context.Connection.Open();
    }

    return context.Connection.BeginTransaction(isolationLevel);
}

Thank to Kim Major for answering the following question. I cannot found any other pages that clearly suggest me to use Entity transaction including main MSDN website (How to: Manage Transactions in the Entity Framework).

How to use transactions with the Entity Framework?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top