简体   繁体   English

如何在asp.net mvc中合并数据库访问和缓存(非静态字段,方法或属性“ Module.dbApp”需要对象引用)

[英]How to combine database access and cache in asp.net mvc (An object reference is required for the non-static field, method, or property 'Module.dbApp')

This is actually 2 questions in one. 这实际上是两个问题合二为一。

I have an asp.net mvc application where I have to load a list of Modules, its just a simple list with ID, modulename and a class name to render it on the view with font awesome. 我有一个asp.net mvc应用程序,我必须在其中加载模块列表,它只是一个包含ID,模块名和类名的简单列表,才能以令人敬畏的字体在视图上呈现它。

My model is like this: 我的模型是这样的:

   public class Module
    {
        [Key]
        public int Id { get; set; }
        public string ModuleName { get; set; }
        public string FontAwesomeClass { get; set; }
    }

Because the module list is a Partial View that will render some icons on the top navigation bar, I dont want that for each refresh of the app, it goes to the DB, so it must be cached(I am using Azure REDIS Cache, not relevant for the question anyway), so instead of calling the DB context directly from the controller, I am calling a Cache Class that will check if the cache object exists, if not it will retrieve it from DB, if it does, it will return it from cache. 因为模块列表是一个局部视图,将在顶部导航栏上显示一些图标,所以我不希望每次刷新应用程序时将其转到数据库,因此必须对其进行缓存(我正在使用Azure REDIS Cache,无论如何都与问题相关),所以我不是直接从控制器调用数据库上下文,而是调用一个缓存类,该类将检查缓存对象是否存在,如果不存在,它将从数据库中检索它,如果存在,它将返回从缓存。

This my solution structure: http://screencast.com/t/uayPYiHaPCav 这是我的解决方案结构: http : //screencast.com/t/uayPYiHaPCav

Here is my controller Module.cs 这是我的控制器Module.cs

public ActionResult GetModules()
    {
        return View(Cache.Module.GetModules());
    }

As you can see the Controller does not have any logic where to get the data from. 如您所见,Controller没有任何逻辑可从何处获取数据。

Here is the Module.cs (on the Cache Namespace) 这是Module.cs(在高速缓存命名空间上)

public class Module
    {
        private AppDataContext dbApp = new AppDataContext();

        //Load modules from cache or from database
        public static List<Models.Module> GetModules()
        {
            IDatabase cache = Helper.Connection.GetDatabase();
            List<Models.Module> listOfModules = (List<Models.Module>)cache.Get("Modules");
            if (listOfModules == null)
            {
                return dbApp.ModuleList.ToList();
            }
            else
            {
                return listOfModules;
            }
        }           
    }

Here I have a compiler error which I am not sure how to best fix it: 这里有一个编译器错误,我不确定如何最好地解决它:

Error CS0120 An object reference is required for the non-static field, method, or property 'Module.dbApp' 错误CS0120非静态字段,方法或属性'Module.dbApp'需要对象引用

So that was my first question. 这是我的第一个问题。

The 2nd question is more about the design pattern, do you consider this correct or not? 第二个问题是关于设计模式的,您是否认为这是正确的? the way I am trying to get the data from Cache, and its actually the Cache class which checks if data is on it or if it has to go to the DB. 我尝试从Cache获取数据的方式,以及它实际上是Cache类,用于检查数据是否在其中或是否必须发送到DB。

First Question: make your private member static 第一个问题:使您的私人成员成为静态成员

private static AppDataContext dbApp = new AppDataContext();

2nd Question: your cache strategy seems pretty standard. 第二个问题:您的缓存策略似乎很标准。 The only thing is that you might want to expire cache data. 唯一的事情是您可能想使缓存数据过期。 For example, the cached data can get old and the longer it stays in the cache the older it gets. 例如,缓存的数据可能会变旧,并且保留在缓存中的时间越长,它就会变得越旧。 You might at some point want to expire it and get fresh data again. 您可能在某个时候想要使其过期并再次获取新数据。

Update: 更新:

@EstebanV for code sample (this off the top of my head, don't assume that it compiles): @EstebanV以获得代码示例(这超出了我的头脑,不要认为它可以编译):

/** 
     ICachedPersonDao abstracts away the caching mechanism 
     away from the core of your application 
**/
public CachedPersonDao : ICachedPersonDao
    {

      private IPersonDao personDao = null;

      public CachedPersonDao(IPersonDao personDao)
      {
          this.personDao = personDao;
      }

      public Person GetPersonById(int id){

          bool isInCache = CACHE.SomeFunctionThatChecksInYourCache(id);
          if (isInCache)
          {
               return CACHE.SomeFunctionThatReturnsTheCachedPerson(id);
          }
          else
          {
               //Well it's not in the cache so let's get it from the DB.
               return this.personDao.GetPersonById(id);
          }
      }
    }

    /** 
       IPersonDao abstracts database communication 
       away from the core of your application 
    **/
    public class PersonDao : IPersonDao
    {
          public Person GetPersonById(int id)
          {
                /** Get the person by id from the DB 
                   through EntityFramework or whatever 
                 **/
          }
    }

Usage: 用法:

In your controller, use ICachedPersonDao if you want to attempt to get from cache or use IPersonDao if you want to get it directly from the database without checking the cache. 在您的控制器,使用ICachedPersonDao如果你想尝试从缓存中获取或使用IPersonDao如果您想直接从数据库中获取它不检查缓存。

Like I said, you should learn Dependency Injection it will help "inject" these dependencies into the classes that uses them. 就像我说的那样,您应该学习依赖注入,它将帮助将这些依赖“注入”到使用它们的类中。

I say again, this is off the top of my head. 我再说一遍,这已经超出了我的头脑。 It won't compile. 它不会编译。 It's just to illustrate the concept. 只是为了说明概念。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 字段初始化程序无法引用ASP.Net MVC Controller中的非静态字段,方法或属性 - A field initializer cannot reference the non-static field, method, or property in ASP.Net MVC Controller 在方法中更改属性时,非静态字段,方法或属性“ Module.action2”需要对象引用 - An object reference is required for the non-static field, method, or property 'Module.action2' when changing property in method 非静态字段,方法或属性需要对象引用 - An object reference is required for the non-static field, method, or property 非静态字段,方法或属性需要对象引用 - An object reference is required for the non-static field, method, or property 非静态字段,方法或属性是否需要对象引用? - An object reference is required for the non-static field, method, or property? 非静态字段,方法或属性需要对象引用 - An object reference is required for the non-static field, method, or property 非静态字段,方法或属性(数据集)需要对象引用 - An object reference is required for the non-static field, method, or property (dataset) 错误:非静态字段,方法或属性需要对象引用 - Error: An object reference is required for the non-static field, method, or property 对象引用是必需的非静态字段,方法或属性错误 - An object reference is required non-static field, method, or property error 非静态字段,方法或属性需要对象引用 - Object reference is required for non-static field, method or property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM