c# – 实体框架:存储实体而不保存到数据库

如何在不保存到数据库的情况下在ObjectContext中存储临时项?

上下文存储在HttpContext中,按类提供:

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"];
    }
}

有两个空页:
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();
    }
}

所以,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();
    }
}

这里CountInSecondPage = 0.

哪里我错了?

最佳答案
我是对的,第二页是第二个请求吗?

在这种情况下,您有一个新的HttpContext.Items集合,并且您上次请求的值消失了.在这种情况下,请考虑使用会话来存储这些值.

脚注:
EntityContext应仅用于一个请求,并且可以出于该原因存储在HttpContext.Items集合中,但绝不能作为Session值存储!在这里存储结果就像计数一样.

转载注明原文:c# – 实体框架:存储实体而不保存到数据库 - 代码日志