Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update an entity in EF across multiple ASP.NET requests without retrieving it again?

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?

like image 930
Jarrette Avatar asked Nov 03 '22 21:11

Jarrette


2 Answers

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

like image 86
Sean Glover Avatar answered Nov 15 '22 07:11

Sean Glover


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()
like image 34
TheGeekYouNeed Avatar answered Nov 15 '22 07:11

TheGeekYouNeed