gpt4 book ai didi

c# - Entity Framework : Storing Entities without saving to Database

转载 作者:太空狗 更新时间:2023-10-29 21:41:40 26 4
gpt4 key购买 nike

如何在不保存到数据库的情况下将临时项目存储在 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)首页.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 集合,并且上次请求中的值已经消失。在这种情况下考虑使用 session 来存储这些值。

脚注:EntityContext 应该只用于一个请求,因此可以存储在 HttpContext.Items 集合中,但绝不能作为 Session 值!只在此处存储结果,例如计数。

关于c# - Entity Framework : Storing Entities without saving to Database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5950486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com