15 мая 2014
Кравченко Виктор

Ошибка «New transaction is not allowed because there are other threads running in the session» (Ошибка при запуске транзакции в соединении поставщика. Подробные сведения см. во внутреннем исключении.) при попытке осуществить запись

VB.NET MVC 3 ASP.NET LINQ
01

Ошибка возникает при попытке осуществить запись изменений в БД — db.SaveChanges(), в случаях, подобных следующему примеру:

02 VB.NET
1
2
3
4
5
6
7
8
9
Dim oldContracts As IEnumerable(Of Contract) = db.Contracts.Where(Function(c) c.ContrID = id) For Each oldContract As Contract In oldContracts Dim newContract As Contract = New Contract newContract.DateCreate = oldContract.DateCreate … db.Contracts.AddObject(newContract)
db.SaveChanges() ' Здесь возникает ошибка
Next
03

Оказывается, что транзакцию блокирует цикл перебора:

04 VB.NET
1
For Each oldContract As Contract In oldContracts
05

Дело в том, что функция Where(Function()...) возвращает результат типа Linq.IQueryable(), который создает транзакцию, которая в свою очередь остается открытой на все время исполнения запроса — на весь цикл перебора. А вызов метода db.SaveChanges() пытается открыть новую транзакцию, при открытой предыдущей и это вызывает исключение. Чтобы «завершить» открытую транзакцию необходимо привести результат к «конечному» типу, например Array или List(Of ...). Для этого необходимо изменить код:

06 VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
'Вариант первый Dim oldContracts As Contract() = db.Contracts.Where(Function(c) c.ContrID = id).ToArray 'Вариант второй Dim oldContracts As List(Of Contract) = db.Contracts.Where(Function(c) c.ContrID = id).ToList 'Или например так... В принципе, то же самое, только более длинный код Dim lstContracts As IEnumerable(Of Contract) = db.Contracts.Where(Function(c) c.ContrID = id) Dim oldContracts = lstContracts.ToArray For Each oldContract As Contract In oldContracts Dim newContract As Contract = New Contract newContract.DateCreate = oldContract.DateCreate … db.Contracts.AddObject(newContract) db.SaveChanges() Next
07

Похожие запросы:

  • New transaction is not allowed because there are other threads running in the session
  • Entity Framework new transaction is not allowed because there are other threads running in the session, multi thread save
  • LINQ to Entities: «New transaction is not allowed because there are other threads running in the session.»
  • Entity Framework Error–New Transaction is not allowed because there are other threads running in the session
comments powered by HyperComments