Sounds easy, right? Here's the scenario...
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 do I access that original object to update it?
HTTP is a stateless protocol and as a result, every request you make to your server needs to rebuild your object graph unless you persist it somewhere. There are many ways to persist data across a web "session". In ASP.NET you can store data in cookies, server side session, viewstate, form variables, and more.
First you would detach your CurrentCoral from the object context when you're done with it in Page_Load
dbQuery.Detach(CurrentCoral)
Then put it in a data store like view state.
Me.ViewState.Add("CurrentCoral", CurrentCoral)
In the next web request when your save button is clicked, retrieve the entity from the view state and attach it to your new object context.
CurrentCoral = CType(Me.ViewState("CurrentCoral"), Coral)
dbQuery.Attach(CurrentCoral)
CurrentCoral.CommonName = strName
dbQuery.SaveChanges()
Please forgive any syntax errors. VB.NET is not my first language! For more details on attaching and detaching entities with Entity Framework see the following article.
Attaching and Detaching Objects
You could put your CurrentCoral object into the ViewState or Session, then retrieve it in the Click event.
Dim oCurrentCorral as Object = ViewState("CurrentCoral")
dbQuery.ObjectStateManager.ChangeObjectState(oCurrentCoral, System.Data.EntityState.Added)
dbQuery.SaveChanges()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With