我有一个带有.NET 4的Windows窗体应用程序和用于数据层的实体框架我需要一个带有事务的方法,但是进行简单的测试我无法使其工作
在BLL中:
public int Insert(List<Estrutura> lista)
{
using (TransactionScope scope = new TransactionScope())
{
id = this._dal.Insert(lista);
}
}
Run Code Online (Sandbox Code Playgroud)
在DAL:
public int Insert(List<Estrutura> lista)
{
using (Entities ctx = new Entities (ConnectionType.Custom))
{
ctx.AddToEstrutura(lista);
ctx.SaveChanges(); //<---exception is thrown here
}
}
Run Code Online (Sandbox Code Playgroud)
"底层提供商在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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助
| 归档时间: |
|
| 查看次数: |
3117 次 |
| 最近记录: |