与实体的交易范围

时间:2012-05-22 13:32:32

标签: c# .net entity

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

在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
   }
}

“底层提供商在Open上失败了。”

有人有什么想法吗?

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

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

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

这是我的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();
            }
        }
    }

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

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

以下是distributed transactions issue的信息。

以下是manually open and close the connection的方法。

一个小代码示例:

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();
}

答案 1 :(得分:-1)

不使用TransactionScope,最好在使用实体框架时使用UnitOfWork模式。请参阅: unit of work pattern

还有;

unit of work and persistance ignorance