我遇到了链接到SQL并更新记录的问题,我认为问题在于当前事务是基于我在循环连接数据上下文的事实:
Using db = New PostcodeLookupModelContainer()
Dim Stores = From b In db.lkpStores Where b.storeId ' = iStoreID ' Order By b.storeId
For Each store In Stores
Debug.Print(store.StorePostcode)
Dim newStore As New lkpStores()
newStore.depotId = store.depotId
newStore.StorePostcode = store.StorePostcode
newStore.depotId = store.depotId
newStore.DepotDistance = store.DepotDistance
db.lkpStores.Attach(newStore)
newStore.DepotDistance = 50
db.SaveChanges()
Next store
End Using
我收到错误的行是db.SaveChanges(),错误是“不允许新事务,因为会话中还有其他线程运行。”
答案 0 :(得分:0)
不要认为你需要附加新对象,因为它已经存在。
db.lkpStores.Attach(newStore)
只需从ForEach循环更新商店对象,然后调用submit
Using db = New PostcodeLookupModelContainer()
Dim Stores = From b In db.lkpStores Where b.storeId ' = iStoreID ' Order By b.storeId
For Each store In Stores
store.DepotDistance = 50
db.SaveChanges()
Next store
End Using
你也可以重构代码
Using db = New PostcodeLookupModelContainer()
Dim store = (From b In db.lkpStores Where b.storeId).SingleOrDefault 'Assumming the storeID is unique
if store isnot nothing then
store.DepotDistance = 50
db.SaveChanges()
end if
End Using
答案 1 :(得分:0)
尝试将“Dim Stores = From b In db.lkpStores Where b.storeId ' = iStoreID ' Order By b.storeId
”转换为List(),然后将其循环