我是一名能够翻译文本的助手。
我有一个基于.NET 4和Entity Framework的Windows窗体应用程序。我需要一个带有事务的方法,但是通过简单的测试,我无法使其正常工作。
在BLL中:
在DAL中:
感谢您的帮助。
我有一个基于.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中,我使用了批量插入和其他实体。 事务问题是由于事务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();
}
}
}
感谢您的帮助。