Search code examples
c#asp.netentity-frameworkhttpcontext

Entity Framework: Storing Entities without saving to Database


How to store temporary item in ObjectContext without saving to database?

Context storing in HttpContext, providing by class:

public static class HttpContextExtension
{
    public static MyEntityDataModelContainer GetMyContext(this HttpContext httpContext)
    {
        if (httpContext.Items["MyEntityDataModelContainer"] == null)
        {
            httpContext.Items.Add("MyEntityDataModelContainer", new MyEntityDataModelContainer());
        }

        return (MyEntityDataModelContainer)httpContext.Items["MyEntityDataModelContainer"];
    }
}

There are two empty pages: 1) FirstPage.aspx.cs:

public class FirstPage : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // crete new item
        MyEntity newTemporaryItem = new MyEntity { MyEntityID = Guid.NewGuid() };
        // attach them to Context
        HttpContext.Current.GetMyContext().MyEntitySet.Attach(newTemporaryItem);
        // save changes
        HttpContext.Current.GetMyContext().SaveChanges();

        // get all attached to Context items
        var addedItems = (from se in HttpContext.Current.GetMyContext().ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged)
                          where se.Entity is MyEntity
                          select se.Entity).AsQueryable();
        int CountInFirstPage = addedItems.Count();
    }
}

So, CountInFirstPage = 1.

2) SecondPage.aspx.cs:

public class FirstPage : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // get added in First page items From HttpContext
        var addedItems = (from se in HttpContext.Current.GetMyContext().ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged)
                          where se.Entity is MyEntity
                          select se.Entity).AsQueryable();
        int CountInSecondPage = addedItems.Count();
    }
}

Here CountInSecondPage = 0.

Where I'm wrong?


Solution

  • Am I right that the second page is a second request?

    In that case you have a new HttpContext.Items collection and your values from the last request are gone. Consider to use a session to store these values in such a case.

    Footnote: The EntityContext should only be used for one request and can be stored in the HttpContext.Items collection for that reason but never as a Session value! Store just results here like the count.