【问题标题】:Entity Framework & MemoryCache实体框架和内存缓存
【发布时间】:2018-10-29 02:17:55
【问题描述】:

我有一个 n 层应用程序 ASP.NET MVC。我在 DAL 中使用实体框架。 所以我决定在 dal 中使用缓存层来提高应用程序的性能。我已经实现了它,但是有一个问题。我将实体放入内存缓存的第一个请求之后,当第二个请求我尝试从缓存中获取实体时,它会抛出对象处置错误。我知道这个错误很正常,因为我不能从缓存中得到它。但我想不出来。 我能做些什么?我应该在 dal 中使用业务对象还是?

“ObjectContext 实例已被释放,不能再用于需要连接的操作”

    public IQueryable<Category> GetAll()
    {
        var cacheKey = string.Format("{0}_{1}", "CategoryRepository", "GetAll");

        var isExists = _cache.Contains(cacheKey) && Const.CacheIsActive;
        if (isExists)
        {
               //At here error: "The ObjectContext instance has been disposed and 
               //can no longer be used for operations that require a connection"
            return _cache.Get<IQueryable<Category>>(cacheKey);
        }
        else
        {
            var obj = _db.Categories;
            _cache.Add(cacheKey, obj);

            return obj;
        }
    }

【问题讨论】:

标签: c# sql-server asp.net-mvc entity-framework caching


【解决方案1】:

在上下文中写

protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            if (options != null)
            {
                options.UseMemoryCache(_cache);
            }
        }

【讨论】:

    猜你喜欢
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    相关资源
    最近更新 更多