How to update an object in EF through several ASP.NET requests without returning it again?

Sounds easy, right? Here is the script ...

Private dbQuery As New ReefEntities

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        CurrentCoral = (From c In dbQuery.Corals Where c.CoralID = intCoralID).FirstOrDefault
       txtCommonName.Text = CurrentCoral.CommonName
    End If
End Sub

Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
    'how do I access the coral from the page load to update it?
   CurrentCoral.CommonName = strName
   dbQuery.SaveChanges()
End Sub

I don’t want to re-query my result, I want to update the query from the page load and then save the changes, right? How to access this source object to update it?

+5
source share
3 answers

HTTP is a stateless protocol and, as a result, every request you make to your server should rebuild the object’s schedule if you don’t save it somewhere. There are many ways to save data through a web session. In ASP.NET you can store data in cookies, on the server side, in the view, in form variables, etc.

CurrentCoral , Page_Load

dbQuery.Detach(CurrentCoral)

, .

Me.ViewState.Add("CurrentCoral", CurrentCoral)

-, , .

CurrentCoral = CType(Me.ViewState("CurrentCoral"), Coral)
dbQuery.Attach(CurrentCoral)
CurrentCoral.CommonName = strName
dbQuery.SaveChanges()

. VB.NET - ! Entity Framework . .

+1

CurrentCoral ViewState Session, Click.

 Dim oCurrentCorral as Object = ViewState("CurrentCoral")
 dbQuery.ObjectStateManager.ChangeObjectState(oCurrentCoral, System.Data.EntityState.Added)
 dbQuery.SaveChanges()
+1

If the request is a postback, the record does not load at all Page_Load- there is no repeated request, since you did not make the request in the request at all. I would say that simply re-requesting in the feedback handler, most likely, the overhead of getting your database once to update is much less than the overhead of sending the whole entity serialized in ViewState all the time.

0
source

All Articles