Entity Framework ASP.net Web Forms Saving Entities in ViewState

Jeryizeerarie

New Member
I have 3 Tables.[*]Customer[*]CustomerAddress[*]CityCustomerAddress is the child table of Customer and there is a Field CityID in CustomerAddress which is linked with City Table.I have created a ADO.net Entity Model using this Database.I have a single Customer page, let say customer.aspx. This page can be used for both Creating a new Customer and for Updating a previously saved Customer.There are 2 sections on page same page, 1st section to display the Customer table fields. And 2nd section is actually a grid showing Customer's Addresses and there is a Add New Address button which un-hides a form, user puts new address information there and submits back the page. I then add new CustomerAddress instance in Customer.CustomerAddress EntityCollection.I am currently keeping the Customer object along with all the related CustomerAddress objects in ViewSate.Since I am using the Entity Framework so I also want to utilize the benefits of linked entities. For example I am binding the Customer.CustomerAddress collection to my GridView which displays currently Added addresses. Since CustomerAddress has the naviational property City, so I am using a Bound field with DataField = "City.CityName", which displays the correct city name, if I add the Customer and related Addresses in ObjectContext.Whenever page posts back, I create the ObjectContext again. Because I am NOT saving it in ViewState or Session.Problem:Now the problem is, whenever I try to add the Customer in ObjectContext it starts giving different kind of errors. So far I have recognized that when I save the CustomerAddress class in ViewState, it saves City object along with CustomerAddress, which then gets loaded back from ViewState. And then when I try to add the Customer entity back on post back it gives error.Also I am NOT sure how to handle the Insert/Update situation, because if this is a new customer then I have to add the Entity in ObjectContext otherwise I have to attach it.Is this correct way, or I need to follow some other approach?My main requirements are,1) Use the linked entities even if the entities state is Added. For example if I add the CustomerAddress in ObjectContext with CityID = 1, then I want to be able to access the Navigational property City to access other fields of City entity, without manually loading City into some DataTable or collection.2) Save the Customer and CustomerAddress in the ViewState to back and forth, and then finally save the changes back to database when user hits the Save buttonThanks
 
Back
Top