开发者

Why does Entity Framework 4.0 require using DTM? Is it possible to do not use it?

开发者 https://www.devze.com 2023-01-23 07:00 出处:网络
I use EF almost one year ago. I just try to use TransactionScope deal with quite complex query like the following code.

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 i开发者_StackOverflow社区t should not be affect from different transaction technic.

Thanks,


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号