I'm creating an Asp.net MVC site using the Entity Framework and am wondering how to keep new and updated entities in memory across multiple requests without committing to the database.
Say, for example a user goes to a view for editing an entity, and on that view they can add children to the entity. I would like to not commit the change to the database until the user clicks the "Save" button on the page.
I've picked up that I'm not to persist the ObjectContext, which I understand. Essentially I want to take an entity, keep it in Session state, or somewhere equivalent, make changes there, then submit those to the database when the user has finished on the page.
Any thoughts on how to do this?
views:
235answers:
2The ViewData collection is a temporary "scratch-pad" for persisting objects across requests. It works in the same manner as the Session object, but is shorter-term in lifetime.
In the default MVC project, you can see an example of this in the Home controller, where it uses the ViewData["Message"] to display a message on the Index view.
I came across this question searching for a similar problem. Just in case anyone else is in the same situation, the accepted answer by Josh E is mistaken - ViewData is NOT persisted across multiple requests, it is only for passing data to the View, which happens within the same request. TempData IS persisted across requests, but values stored in it are cleared after being read once.
I'm not familiar enough with the Entity Framework to know whether it's supported, but you can store any (serializable?) object in the Session. However, the lifetime of those objects depends on the Session lifetime unless you remove them manually. Also, this can take up a significant amount of memory. I believe the most desirable method is to use a persistence framework which can manage this for you. I don't know whether the Entity Framework can do it. For those of us stuck with ADO, I have yet to find a good solution.