【发布时间】:2012-10-28 22:56:20
【问题描述】:
我们正在通过 WCF 从客户端 (Silverlight) 接收文件,并在服务器端解析该文件。文件中的每一行都被转换为一个对象并存储到数据库中。如果文件非常大(超过 10000 个条目),我会收到以下错误(MSSQLEXPRESS):
与当前连接关联的事务已完成但尚未处理。必须先处理事务,然后才能使用连接执行 SQL 语句。
我尝试了很多(TransactionOptions 超时设置等),但没有任何效果。上述异常消息要么在 3000 之后引发,有时在 6000 个对象处理之后引发,但我无法成功处理所有对象。
我附上了我的来源,希望有人有想法并可以帮助我:
public xxxResponse SendLogFile (xxxRequest request
{
const int INTERMEDIATE_SAVE = 100;
using (var context = new EntityFramework.Models.Cubes_ServicesEntities())
{
// start a new transactionscope with the timeout of 0 (unlimited time for developing purposes)
using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew,
new TransactionOptions
{
IsolationLevel = System.Transactions.IsolationLevel.Serializable,
Timeout = TimeSpan.FromSeconds(0)
}))
{
try
{
// open the connection manually to prevent undesired close of DB
// (MSDTC)
context.Connection.Open();
int timeout = context.Connection.ConnectionTimeout;
int Counter = 0;
// read the file submitted from client
using (var reader = new StreamReader(new MemoryStream(request.LogFile)))
{
try
{
while (!reader.EndOfStream)
{
Counter++;
Counter2++;
string line = reader.ReadLine();
if (String.IsNullOrEmpty(line)) continue;
// Create a new object
DomainModel.LogEntry le = CreateLogEntryObject(line);
// an attach it to the context, set its state to added.
context.AttachTo("LogEntry", le);
context.ObjectStateManager.ChangeObjectState(le, EntityState.Added);
// while not 100 objects were attached, go on
if (Counter != INTERMEDIATE_SAVE) continue;
// after 100 objects, make a call to SaveChanges.
context.SaveChanges(SaveOptions.None);
Counter = 0;
}
}
catch (Exception exception)
{
// cleanup
reader.Close();
transactionScope.Dispose();
throw exception;
}
}
// do a final SaveChanges
context.SaveChanges();
transactionScope.Complete();
context.Connection.Close();
}
catch (Exception e)
{
// cleanup
transactionScope.Dispose();
context.Connection.Close();
throw e;
}
}
var response = CreateSuccessResponse<ServiceSendLogEntryFileResponse>("SendLogEntryFile successful!");
return response;
}
}
【问题讨论】:
-
尝试重构该代码,使其更具可读性。没有人喜欢在你发布的混乱中徘徊。这是一本可以帮助您创建更简洁代码的好书:amzn.to/1G1pk。看看这个视频:bit.ly/irhPnl.
标签: entity-framework transactions