我是實體框架的新手,並且正在擴展現有的代碼庫。我使用jQuery將所需的信息傳遞迴服務器ajaxy樣式,因此我不能使用TryUpdateModel()
。下面的代碼:將對實體模型的更改保存到數據庫
<HttpPost()>
Function UpdateRoster() As JsonResult
Dim model As New Models.ViewModels.PlayerAdmin
Dim jsonString As String = Request.Form("json")
model = Deserialise(Of Models.ViewModels.PlayerAdmin)(jsonString)
For Each playerAdminPlayer As Models.ViewModels.PlayerAdminPlayer In model.Roster
Dim playerToTeam As New DAL.PlayersToTeam
Dim player As DAL.Player = PlayerAdminManager.GetPlayerById(playerAdminPlayer.PlayerId)
player.FirstName = playerAdminPlayer.FirstName
PlayerAdminManager.SaveChanges()
Next playerAdminPlayer
Dim playerAfter As DAL.Player = PlayerAdminManager.GetPlayerById(model.Roster.First.PlayerId)
Return Json(New With {.success = False, .message = playerAfter.FirstName})
End Function
Deserialise
是一個輔助功能是將輸入的JSON字符串到VB對象。
事情似乎正常工作player
成功從數據庫加載和playerAdminPlayer
是來自JSON字符串的正確對象。然而,當我打電話給PlayerAdminManager.SaveChanges()
(它只是通過調用db.SaveChanges()時,結果始終爲0,即使有變化(不確定是否有此變化)也不知道是否應該這樣做。變化實際上被保存,它似乎正常工作,在playerAfter.FirstName
是最近更新的名字。從數據庫
PlayerAdminManager.GetPlayerById(integer)
拉,所以我會認爲,因爲變化在playerAfter
觀察到,這些變化被保存到DB。然而,當我重新加載網頁(從DB拉),舊值在那裏。
任何想法?
下面是一些功能我提到:
Function GetPlayerById(ByVal Id As Integer) As DAL.Player
Return Container.Players.Where(Function(o) o.PlayerId = Id And o.IsVisible = True).SingleOrDefault
End Function
Sub SaveChanges()
Dim numberOfChanges As Integer = Container.SaveChanges()
Debug.WriteLine("No conflicts. " & numberOfChanges.ToString() & " updates saved.")
End Sub
EDIT
集裝箱代碼:
Private _Container As DAL.LateralSportsContainer
Protected ReadOnly Property Container As DAL.LateralSportsContainer
Get
If _Container Is Nothing Then
Dim connStr As New System.Data.EntityClient.EntityConnectionStringBuilder
connStr.ProviderConnectionString = Web.Configuration.WebConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
connStr.Metadata = "res://*/Lateral.csdl|res://*/Lateral.ssdl|res://*/Lateral.msl"
connStr.Provider = "System.Data.SqlClient"
_Container = New DAL.LateralSportsContainer(connStr.ConnectionString)
End If
Return _Container
End Get
End Property
容器是你的DataContext的靜態或緩存實例?您能否顯示與創建和存儲Container相關的代碼? – wonkim00
@ wonkim00 - 是你需要的嗎? –
是的,這就是我正在尋找的東西,但我看不出有什麼不對。我不認爲這是一個DataContext生存期管理問題 - 它被創建並緩存,隨後對PlayerAdminManager上方法的調用使用緩存實例,所以更改跟蹤應該處於活動狀態,並且不需要附加修改後的對象。抱歉。 – wonkim00