具有实体的事务范围

本文关键字:事务 范围 实体 | 更新日期: 2023-09-27 18:35:09

我有一个Windows表单应用程序,其中包含.NET 4和数据层的实体框架我需要一种方法来处理事务,但是进行简单的测试我无法使其工作

在 BLL 中:

public int Insert(List<Estrutura> lista)
{
    using (TransactionScope scope = new TransactionScope())
    {
            id = this._dal.Insert(lista);
    }
}

在 DAL 中:

public int Insert(List<Estrutura> lista)
{
   using (Entities ctx = new Entities (ConnectionType.Custom))
   {
     ctx.AddToEstrutura(lista);
     ctx.SaveChanges(); //<---exception is thrown here
   }
}

"基础提供程序在打开时失败。"

有人有什么想法吗?

问题已解决 - 我的解决方案

通过一些更改解决了我的问题。在我的一个 DAL 中,我使用批量插入和其他实体。问题事务的发生是由于大部分事务(事务sql)不了解事务范围而发生的所以我在 DAL 中分离了实体,并在运行一些琐碎的事情中使用了 sql 事务。执行标量 ();

我相信这不是最优雅的方式,但解决了我的问题交易。

这是我的 DAL 的代码

   using (SqlConnection sourceConnection = new SqlConnection(Utils.ConnectionString()))
   {
        sourceConnection.Open();
        using (SqlTransaction transaction = sourceConnection.BeginTransaction())
        {
            StringBuilder query = new StringBuilder();
            query.Append("INSERT INTO...");
            SqlCommand command = new SqlCommand(query.ToString(), sourceConnection, transaction);
            using (SqlBulkCopy bulk = new SqlBulkCopy(sourceConnection, SqlBulkCopyOptions.KeepNulls, transaction))
            {                           
                bulk.BulkCopyTimeout = int.MaxValue;
                bulk.DestinationTableName = "TABLE_NAME";
                bulk.WriteToServer(myDataTable);
                StringBuilder updateQuery = new StringBuilder();
                //another simple insert or update can be performed here
                updateQuery.Append("UPDATE... ");
                command.CommandText = updateQuery.ToString();
                command.Parameters.Clear();
                command.Parameters.AddWithValue("@SOME_PARAM", DateTime.Now);
                command.ExecuteNonQuery();
                transaction.Commit();
            }
        }
    }

感谢您的帮助

具有实体的事务范围

根据全

能的谷歌的说法,EF似乎会在每次调用数据库时打开/关闭连接。由于它这样做,它将事务视为使用多个连接(使用分布式事务)。解决此问题的方法是在使用时手动打开和关闭连接。

下面是有关分布式事务问题的信息。

下面介绍如何手动打开和关闭连接。

一个小代码示例:

public int Insert(List<Estrutura> lista)
{
    using (TransactionScope scope = new TransactionScope())
    {
        using (Entities ctx = new Entities (ConnectionType.Custom))
        {
            ctx.Connection.Open()
            id = this._dal.Insert(ctx, lista);
        }
    }
}
public int Insert(Entities ctx, List<Estrutura> lista)
{
     ctx.AddToEstrutura(lista);
     ctx.SaveChanges();
}

与其使用 TransactionScope,不如在使用实体框架时使用 UnitOfWork 模式。 请参考:工作单元模式

还有;

工作单元和持久性无知