【发布时间】:2013-12-14 17:21:49
【问题描述】:
假设我有一个应用程序,例如一个网站,我的 objectcontext 在请求期间离开。我用 EF 加载的一些数据应该被缓存以避免读取到 DB 并提高性能。
好的,我用 EF 读取了我的数据,我将我的对象放入缓存中(说是 AppFabric,而不是在内存缓存中),但是可以延迟加载的相关数据现在为空(并且访问此属性会导致空引用异常) .我不想在一个请求中加载所有内容,因为它会太长,所以我想保持按需加载,一旦读取,我想用新获取的数据完成缓存。
注意:
- 只有读取操作,没有创建/更新/删除。
- 不想使用像 Jarek Kowalski 制作的“EF Provider Wrappers”这样的二级缓存
我该怎么做?
编辑:我已经用北风数据库构建了这个示例,它正在工作:
class Program
{
static void Main(string[] args)
{
// normal use
List<Products> allProductCached = null;
using (NORTHWNDEntities1 db = new NORTHWNDEntities1())
{
allProductCached = db.Products.ToList().Clone<DbSet<Products>>();
foreach (var product in db.Products.Where(e => e.UnitPrice > 100))
{
Console.WriteLine(product.ProductName + " => " + product.Suppliers.CompanyName);
}
}
// try to use cache, but missing Suppliers
using (NORTHWNDEntities1 db = new NORTHWNDEntities1())
{
foreach (var product in allProductCached.Where(e => e.UnitPrice > 100))
{
if (product.Suppliers == null)
product.Suppliers = db.Suppliers.FirstOrDefault(s => s.SupplierID == product.SupplierID).Clone<Suppliers>();
Console.WriteLine(product.ProductName + " => " + product.Suppliers.CompanyName);
}
}
// try to use full cache
using (NORTHWNDEntities1 db = new NORTHWNDEntities1())
{
foreach (var product in allProductCached.Where(e => e.UnitPrice > 100))
{
Console.WriteLine(product.ProductName + " => " + product.Suppliers.CompanyName);
}
}
}
}
public static class Ext
{
public static List<Products> Clone<T>(this List<Products> list)
{
return list.Select(obj =>
new Products
{
ProductName = obj.ProductName,
SupplierID = obj.SupplierID,
UnitPrice = obj.UnitPrice
}).ToList();
}
public static Suppliers Clone<T>(this Suppliers obj)
{
if (obj == null)
return null;
return new Suppliers
{
SupplierID = obj.SupplierID,
CompanyName = obj.CompanyName
};
}
}
问题是我必须复制所有内容(不丢失属性)并在任何地方测试该属性是否为 null 并加载所需的属性。我的代码当然越来越复杂,所以如果我错过了什么,那将是一个问题。没有其他解决方案?
【问题讨论】:
-
为什么在使用空对象之前不做一些检查。如果没有数据 - 加载并缓存它?
-
我没有上下文了
-
那么如果你没有上下文了,你会用什么方法来查找数据?
-
我希望我可以使用同一个对象而不做任何事情
标签: c# caching entity-framework-4