【问题标题】:caching problem in entity framework 4实体框架4中的缓存问题
【发布时间】:2010-01-26 12:16:22
【问题描述】:
我正在使用实体框架 4 从 DB 创建实体。
我有 2 个实体上下文要连接到数据库。
假设 context1 和 context2
但是,当我执行以下步骤时,
1. 从 context1 中获取数据
2. 从 context2 中获取相同的数据行
3. 更新相同的数据行到context1
4. 从 context2 中获取相同的数据行
在步骤 3 中更新后,context2 不会改变。
我猜 context2 缓存了数据。不是每次都从 db 获取数据。
如何解决?
谢谢~
【问题讨论】:
标签:
.net
entity-framework-4
【解决方案1】:
Entity Context 只从数据库中获取一次数据,然后缓存在内存中。
要从数据库中获取数据,您必须首先在 Context1 上调用 SaveChanges()。然后,调用Refresh(RefreshMode.StoreWins, Context2.EntityToRefresh)获取context2中的数据库值。
您还可以使用共享/静态上下文进行查询,因为您可以确保所有查询都具有相同的数据。
你可以这样实现
public class SharedObjectContext
{
private readonly WestwindEntities context;
#region Singleton Pattern
// Static members are lazily initialized.
// .NET guarantees thread safety for static initialization.
private static readonly SharedObjectContext instance = new SharedObjectContext();
// Make the constructor private to hide it.
// This class adheres to the singleton pattern.
private SharedObjectContext()
{
// Create the ObjectContext.
context = new WestwindEntities();
}
// Return the single instance of the ClientSessionManager type.
public static SharedObjectContext Instance
{
get
{
return instance;
}
}
#endregion
public WestwindEntities Context
{
get
{
return context;
}
}
}
【解决方案2】:
您必须致电 SaveChanges() 来保存更改(返回数据库)。
此外,如果您已经枚举了步骤 2 中的集合,那么即使您将更改保存回数据库,您也不会获得步骤 3 中的更新。