空在HttpRuntime.Cache.Add值 [英] Null as value in HttpRuntime.Cache.Add

查看:349
本文介绍了空在HttpRuntime.Cache.Add值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要为一些键存储空在 HttpRuntime.Cache ,因为我不想再去数据库,发现没有该键的条目。

I want to store null for some of the keys in HttpRuntime.Cache as I dont want to again go to Database to find that there is no entry for that key.

所以第一次,它进入数据库,并填充缓存。 ,其目的是使用缓存的数据,而不是做数据库调用服务于以下呼叫

So first time, it goes to database and fills the cache. The intent is to serve the following calls using cached data instead of doing the database call.

下面是我用下面的代码:

Here is the code that I am using the following:

            Info info = null;
        if (HttpRuntime.Cache["Info_" + id.ToString() + "_" + quantity.ToString()] != null)
            info = HttpRuntime.Cache["Info_" + id.ToString() + "_" + quantity.ToString()] as Info;
        if (info == null)
        {
            info = (from dd in dc.Infos
                              where dd.id == id && dd.active == true && dd.quantitytooffset == quantity
                              select dd).SingleOrDefault();
            HttpRuntime.Cache.Add("Info_" + id.ToString() + "_" + quantity.ToString(), info, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);
        }



的代码,即HttpRuntime.Cache.Add最后一行抛出一个System.ArgumentNullException :值不能为空

The last line of code i.e. HttpRuntime.Cache.Add throws an System.ArgumentNullException: Value cannot be null.

如果这个任何想法是可能的,或者我需要使用其他数据结构来存储空值,并期待以后

Any idea if this is possible or I need to use other datastructure to store null values and look up later?

推荐答案

您可以使用自己的空的价值,将它放在缓存中。
为例,

You could use your own "null" value to place into cache. For example,

private static Info NULL_INFO = new Info();



然后,你可以用这个来代替在HttpRuntime.Cache.Add空,后来从缓存中检索检查后你没有得到你的NULL_INFO

Then you could use that instead of null in HttpRuntime.Cache.Add and later after retrieval from cache check that you didn't get your NULL_INFO

if ( info == NULL_INFO) // if you don't have equality operator overloaded, otherwise you'd better use ReferenceEquals() 
    // return empty data
else if (info == null)
    // proceed with try to load from database

这篇关于空在HttpRuntime.Cache.Add值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆