2012-12-21 121 views
2

我遇到鏈接到SQL和更新記錄的問題,我認爲問題是與當前事務的基礎上,我通過連接的數據上下文循環:LINQ到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

你是否在第二次循環中得到錯誤? – ChrisF

回答

0

嘗試轉換你的 「Dim Stores = From b In db.lkpStores Where b.storeId ' = iStoreID ' Order By b.storeId」 到列表()然後循環它

+0

工作的一種享受,謝謝。 – MAO

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 
+0

我以爲也試過了,它給了我同樣的錯誤:'不允許新的事務,因爲會話中有其他線程正在運行。' – MAO

+0

你仍然得到重構代碼的錯誤? –

+0

是的 - 下面的評論固定它,我需要將其更改爲ToList()列表 – MAO