我有以下代码:
Dim dbHousing As New dcHousingDataContext
Dim pullresidents = From p In dbHousing.webResidents _
Select p.dorm_building, p.dorm_room, p.occupantnum _
Order By dorm_building, dorm_room
Dim j as integer = 1
Dim previous As String = ""
For Each row In pullresidents
If previous = "" Then
Dim wResident As New webResident
wResident.occupantnum = j
dbHousing.SubmitChanges()
j = j + 1
previous = row.dorm_building & " " & row.dorm_room
Else
If previous = row.dorm_building & " " & row.dorm_room Then
Dim wResident As New webResident
wResident.occupantnum = j
dbHousing.SubmitChanges()
j = j + 1
Else
Dim wResident As New webResident
j = 1
wResident.occupantnum = j
dbHousing.SubmitChanges()
j = j + 1
previous = row.dorm_building & " " & row.dorm_room
End If
End If
Next
当我运行它时,查看调试器一切看起来都没问题但是当我检查数据库表时它应该插入 - 列值(对于occupantnum)没有改变 - 它们都是空的!
不确定这是否相关,但请注意我现在已将j更新为显式为整数。我注意到在调试时wResident.occupantnum显示为Type“Integer?” - 但这似乎没有任何区别 - 当我重新运行它仍然说类型“整数?”
答案 0 :(得分:2)
使用For Each row In pullresidents
迭代所有提取的对象,但永远不会修改row
。因此,没有可以发送回数据库的更改。
答案 1 :(得分:2)
我认为你在这里做得太多了。
你只想改变行,对吗?
尝试制作:
Dim wResident As New webResident
wResident.occupantnum = j
dbHousing.SubmitChanges()
j = j + 1
进入这个:
row.occupantnum = j
dbHousing.SubmitChanges()
j = j + 1
答案 2 :(得分:1)
如果这是错误的,请原谅我 - 但是如果你要保存它们,你不必将新创建的“webResident”对象与上下文相关联吗?我看不出dbHousing.SubmitChanges()如何保存它不知道的webResidents。
答案 3 :(得分:1)
Dave,在提交更改之前,您需要先将新的webResident对象插入到表中。
dbHousing.webResidents.InsertOnSubmit(webResident);