在LINQ中处理null到SQL查询[英] handling a null in linq to sql query

本文是小编为大家收集整理的关于在LINQ中处理null到SQL查询的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有这样的对象:

public class MyObject{

  public int Prop1 {get;set;}
}

我正在做一个linq到SQL查询,该查询返回这样的myObject列表:

var TheQuery = from ....
               where ....
               select new MyObject()
               {

                 Prop1 = (...... ).Sum( d => d)

               }.ToList();

问题是prop1是一个子查询的总和,有时可能没有返回,总和为null,不能分配给prop1,因为它是int.

这是一个好方法.

感谢您的建议.

推荐答案

如何使用范围变量:

var TheQuery = from ....
               where ....
               let subquery = (...... )
               select new MyObject()
               {

                 Prop1 = subquery!=null ? (subquery.Sum( d => d) ?? 0) : 0;

               }.ToList();

其他推荐答案

我只会将您的财产提升为int?.您一无所有,最好将其表示为零.理由是,应该有可能拥有一个实际的总和为0.在这种情况下,您没有实际值的总和,因此保持无效结果允许您保留此差异.

否则,您可能会考虑(假设查询将值返回可作为空的)在结果中调用.GetValueOrDefault(),这将在数字类型的情况下将null值正常化为0.

本文地址:https://www.itbaoku.cn/post/1556899.html

问题描述

I have an object like this:

public class MyObject{

  public int Prop1 {get;set;}
}

I'm doing a linq to sql query that returns a list of MyObject like this:

var TheQuery = from ....
               where ....
               select new MyObject()
               {

                 Prop1 = (...... ).Sum( d => d)

               }.ToList();

The problem is that Prop1 is a sum of a subquery and sometimes there might be nothing returned and the Sum is null, which can't be assigned to Prop1 because it's an int.

What's a good way around this.

Thanks for your suggestions.

推荐答案

how about using a range variable:

var TheQuery = from ....
               where ....
               let subquery = (...... )
               select new MyObject()
               {

                 Prop1 = subquery!=null ? (subquery.Sum( d => d) ?? 0) : 0;

               }.ToList();

其他推荐答案

I would simply promote your property to an int?. You have the sum of nothing, it's best to represent that as a null. The rationale is that it should be possible to have an actual sum that is 0. In this case, you do not have a sum of actual values, so keeping the null result allows you to preserve this difference.

Otherwise, you might consider (assuming the query returns the value as a nullable) invoking .GetValueOrDefault() on the result, which would normalize a null value to 0 in the case of a numeric type.