【问题标题】:Referencing null from somewhere I didn't know where从我不知道在哪里的地方引用 null
【发布时间】:2015-12-22 11:48:01
【问题描述】:

我以为我涵盖了所有无效的可能性,但是这一行:

double indicatorValue = 
    step2.Count() > 0 ? step2.Sum(iv => ((double?)iv.Value) ?? 0d) : 0d;

给我这个错误:

无法创建类型为“System.Int32[]”的空常量值。此上下文仅支持实体类型、枚举类型或原始类型。

拜托,我已经阅读了一些帖子,但没有人指出正确的方法。

编辑:相关代码?

var step1 = db.IndicatorValues
    .Where(iv =>
        iv.Year == _ano &&
        iv.IdIndicator == item.IdIndicator &&
        idSites.Contains(iv.IdSite)
    );

var step2 = step1.Where(iv => 
    (isYTD == true ? iv.Month <= _mes : iv.Month == _mes)
);

【问题讨论】:

标签: c# entity-framework linq


【解决方案1】:

我可以看到的“空”情况如下:

class Program
{

    class Test
    {
        public decimal? Value { get; set; }
    }

    static void Main(string[] args)
    {
        var step2 = new Test[] { null };

        double indicatorValue = step2.Count() > 0 ? step2.Sum(iv => ((double?)iv.Value) ?? 0d) : 0d;

        Console.WriteLine(indicatorValue);
    }
}

这给了我 NullReference 异常

为了进一步诊断您的问题,我建议在调试阶段而不是表达式中的 step2 变量来使用 step2Test = step2.ToArray()

在获取数组实例的阶段,你可能会遇到和你描述中一样的错误,那么与indicatorValue计算的逻辑无关

关于int数组中null的错误可以在这里:idSites.Contains(iv.IdSite) 可能的问题iv.IdSite 在特定情况下为空

请尝试以下方法

idSites.Contains(iv.IdSite) 

iv.IdSites == null ? false : ( idSites == null ? false : idSites.Contains(iv.IdSite))

【讨论】:

  • 你说得对,我的int[] idSites 在某处为空。我已经为此添加了一个 if 并且现在一切正常。我为之前没有看到它而感到尴尬...非常感谢老兄!!
  • 那么你应该替换这个指令。会更新我的答案
【解决方案2】:

step1step2IQueryable 而不是 IEnumerable 因此 Linq 想要将 ((double?)iv.Value) ?? 0d 转换为 SQL 语句。

根据代码的其余部分(step1step2 用于其他用途),您可以通过以下方式解决此问题:

一个。将step2 转换为内存中的集合(例如使用.ToList()

b.在步骤 2 中过滤 null 的 IndicatorValues。

c。 double indicatorValue = step2.Count() &gt; 0 ? step2.Where(iv =&gt; iv.HasValue).Sum(iv =&gt; iv.Value) : 0d;

不确定iv.Value 是什么类型,为什么需要将其转换为双精度类型?但其中一种解决方案可能会奏效。

【讨论】:

  • 奇怪,我试过你的a-fix,错误就到了它的行。 =/
  • 也谢谢你.. 请注意,Visual Studio 拒绝 iv.HasValue 为无法识别。
猜你喜欢
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多