我有一个带有 .NET 4 和数据层 Entity Framework 的 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
}
}
“底层提供者打开失败。”
有人有什么想法吗?
问题已解决 - 我的解决方案
我通过一些更改解决了我的问题。 在我的一个 DAL 中,我使用了 Bulk Insert 和其他 Entity。 问题交易的发生是因为交易的大部分(交易 sql)不理解交易范围 所以我将DAL中的Entity分离出来,在其运行中使用了一些琐碎的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 似乎会在每次调用数据库时打开/关闭连接。由于这样做,它将把事务视为使用多个连接(使用分布式事务)。解决此问题的方法是在使用时手动打开和关闭连接。
这是关于 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();
}
关于c# - 与实体的交易范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10703111/