在Cache.insert存在的地方,添加迁移或更新数据库失败

时间:2014-12-22 19:27:47

标签: c# entity-framework asp.net-mvc-4 ef-migrations

我正在尝试运行add-migration命令并收到此错误:

PM> add-migration LatestModel
System.NullReferenceException: Object reference not set to an instance of an object.

这行代码出错:

 public static string WebText(string key)
    {
        //Is value in cache?
        string outputValue;
        if (!CacheHelper.Get(key, out outputValue))
        {
            var str = StringsService.GetResource(value);

           HttpContext.Current.Cache.Insert(
           key,
           outputValue,
           null,
           System.Web.Caching.Cache.NoAbsoluteExpiration,
           TimeSpan.FromMinutes(60));

            return str;

        }

        return outputValue;
    }

现在,函数WebText只是从数据库表中获取一个值,但是,我不知道为什么实体框架试图使用HttpContect行来构建或执行任何操作。

错误抛出

System.NullReferenceException: Object reference not set to an instance of an object.
at PL_AnnexA_Application.Models.Helpers.WebtextHelpers.WebText(String key) in
Helpers.cs:line 36   
at System.ComponentModel.DisplayNameAttribute.GetHashCode()
at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
at System.Linq.Set`1.InternalGetHashCode(TElement value)
at System.Linq.Set`1.Find(TElement value, Boolean add)
at System.Linq.Enumerable.<ExceptIterator>d__99`1.MoveNext()
at System.Linq.Enumerable.<OfTypeIterator>d__aa`1.MoveNext()
Line 36 is

HttpContext.Current.Cache.Insert(

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

看起来你正在覆盖属性中的某个GetHashCode()方法并在其中调用WebText方法。在进行迁移时,散列码可能在EF内部由某处使用。是的,当前的http上下文在那时将为NULL,因为它可能在全局asax的Application_Start中执行。

一种解决方案是删除你的GetHashCode覆盖并解决你在其他地方的必要性。

GetHashCode出现在您的堆栈跟踪中。

答案 1 :(得分:1)

由于我真的需要缓存功能和displaytext覆盖,我意识到只检查HttpContect.Current在缓存例程中是否为空并且完成了工作。我责怪今天的15小时编码。感谢Anshul的指针。