将对实体模型的更改保存到数据库

时间:2011-11-11 18:38:33

标签: asp.net database entity-framework

我是Entity Framework的新手,正在扩展现有的代码库。我正在使用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是我尝试查看是否实际保存了更改。它似乎工作正常,因为playerAfter.FirstName是新更新的名字。

PlayerAdminManager.GetPlayerById(integer)来自数据库,因此我认为,由于在playerAfter中观察到更改,因此这些更改已保存到数据库中。但是,当我重新加载网页(从数据库中提取)时,旧的值就在那里。

有什么想法吗?

以下是我提到的一些功能:

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

编辑

货柜代码:

 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

1 个答案:

答案 0 :(得分:0)

原来我使用的是非静态(共享)Container.我有2 Manager个类,这些类都是从BaseManager类继承的Container被定义的。我在一个Manager中执行查询命令并保存在另一个中。

卫生署!