我需要在数据库中插入一些行,如果行包含错误 - 所有更改都需要回滚。我在考虑使用Parallel类。这是我的代码
class Program
{
static void Main(string[] args)
{
List<string> results = new List<string>();
string[] lines = File.ReadAllLines("d:\\opers2.txt");
using (TransactionScope trans = new TransactionScope())
{
System.Threading.Tasks.Parallel.For(0, lines.Count(), i =>
{
string[] parts = lines[i].Split('\t');
string answer = LoadOper(parts[9], parts[7], parts[0]);
if (!string.IsNullOrEmpty(answer))
results.Add(answer);
});
//trans.Complete();
}
}
static string LoadOper(string typeName, string summ, string operDate)
{
System.Transactions.Transaction trans = System.Transactions.Transaction.Current;
string answer = trans == null ? "NULL" : "TRANSACTION";
using (OperEntities context = new OperEntities())
{
try
{
DateTime dt = DateTime.Parse(operDate);
decimal summa = Decimal.Parse(summ);
OperationType type = context.OperationTypes.FirstOrDefault(t => t.name == typeName);
Operation oper = new Operation()
{
dt_oper = dt,
summ = summa,
OperationType = type
};
context.Operations.AddObject(oper);
context.SaveChanges();
}
catch (Exception ex)
{
return answer + " " + ex.Message;
}
}
return answer;
}
}
但有些线程在LoadOper函数中有Transaction.Current = null。
为什么?