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?
Insert Data Add methods add a new entity to a context (instance of DbContext) which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students. Add(std) adds a newly created instance of the Student entity to a context with Added EntityState.
In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction. The following example demonstrates this.
The Entity state represents the state of an entity. An entity is always in any one of the following states. Added: The entity is marked as added. Deleted: The entity is marked as deleted.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With