Entities, Viewstate and postback

I was fiddling with Entity Framework in a website and was happy to see how smoothly objects serialize (binary serialization) across postbacks.

Query for one customer along with their SalesOrderHeaders:

  Dim query = (From cust In aw.Customer.Include(“SalesOrderHeader”) Where cust.CustomerID = 151)

Grab that customer into an object:

Note, I’ve found a problem with using .First in the query… Include is not working, so this is a temporary long way around…

  For Each c In query
    cust=c
  Next

Now shove it in viewstate

  ViewState.Add(“mycust”,c)

Postback, then recall the customer:

 cust = ViewState(“mycust”)

Be sure that cust is explicitly cast to a Customer.

You will find that not only is the customer in tact with it’s EntityKey, but all of the SalesOrder headers are there as well. So as far as I can tell, it was retained in its entirety.

Be careful however with assumptions about object state!

If you make a change to the object before adding it to ViewState, when you rehydrate the object, the state information won’t survive. This is expected behavior. The ObjectContext is responsible for managing the state of it’s objects. When you detach, you lose the state.

I’ve been playing with different ways of dealing with that if you care at all about concurrency when you do updates – using SaveChanges or using stored procedures. You can see a very long discussion of this in the forums if you are interested.

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.