2

我在链接到 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() 并且错误是“不允许新事务,因为会话中还有其他线程正在运行。”

4

2 回答 2

0

不要认为您需要附加新对象,因为它已经存在。

db.lkpStores.Attach(newStore)

只需从 ForEach 循环更新存储对象并调用提交

   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
于 2012-12-21T15:06:20.480 回答
0

尝试将您的“ Dim Stores = From b In db.lkpStores Where b.storeId ' = iStoreID ' Order By b.storeId”转换为 List() 然后循环它

于 2012-12-21T15:09:33.210 回答