我有一个.NET Core 2.1应用程序。在Startup.cs
配置方法中,我使用:
services.AddDbContext<ApplicationDbContext>(options =
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...
services.AddMemoryCache();
然后在我的控制器中
public class DropDownListController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IMemoryCache _memoryCache;
private const string ProvidersCacheKey = "providers";
private const string AgenciesCacheKey = "agencies";
public DropDownListController(ApplicationDbContext context, IMemoryCache memoryCache )
{
_context = context;
_memoryCache = memoryCache;
}
}
以及在控制器中,用于获取下拉列表的方法:
public JsonResult GetProvider()
{
IEnumerable<DropDownListCode.NameValueStr> providerlist;
if (_memoryCache.TryGetValue(ProvidersCacheKey, out providerlist))
{
return Json(providerlist);
}
else
{
MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddDays(30);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;
DropDownListCode um = new DropDownListCode(_context);
var result = um.GetProviderList();
_memoryCache.Set(ProvidersCacheKey, result);
return Json(result);
}
}
当我在行上设置断点时:
return Json(providerlist);
我看到ProvidersCacheKey
在_memoryCache
中,但没有价值。
数据怎么了?
当我在_memoryCache
上进行快速监视时,可以看到DbContext
对象被破坏了。但是怎么可能,代码工作正常,但是缓存对象没有我保存的数据。
任何帮助将不胜感激。
答案 0 :(得分:0)
获取提供者的方法是:
public IEnumerable<NameValueStr> GetProviderList()
{
var providerlist = (from a in _context.AgencyProvider
where a.Provider == a.AgencyId
select new NameValueStr
{
id = a.Provider,
name = a.Name
});
return providerlist.Distinct();
}
在调用方法中添加“ ToList()”有效:
MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;
DropDownListCode um = new DropDownListCode(_context);
var result = um.GetProviderList().ToList();
_memoryCache.Set(ProvidersCacheKey, result);
return Json(result);
所有功劳归于史蒂夫·皮(Steve Py)...谢谢先生!