Null value handling in linq to sql query

I have an object like this:

public class MyObject{ public int Prop1 {get;set;} } 

I make a linq to sql query that returns a MyObject list as follows:

 var TheQuery = from .... where .... select new MyObject() { Prop1 = (...... ).Sum( d => d) }.ToList(); 

The problem is that Prop1 is the sum of the subquery, and sometimes nothing can be returned, and Sum is null, which Prop1 cannot be assigned because it is int.

How good to do it.

Thanks for your suggestions.

+1
source share
2 answers

how to use range variable:

 var TheQuery = from .... where .... let subquery = (...... ) select new MyObject() { Prop1 = subquery!=null ? (subquery.Sum( d => d) ?? 0) : 0; }.ToList(); 
+1
source

Would I just push your property to int? . You have the sum of nothing, it is better to represent this as zero. The rationale is that it should be possible to have an actual amount of 0. In this case, you do not have the sum of the actual values, so saving a zero result allows you to save this difference.

Otherwise, you might think (assuming the query returns the value as nullable) by calling .GetValueOrDefault() on a result that normalizes the null value to 0 in the case of a numeric type.

+1
source

Source: https://habr.com/ru/post/1486351/


All Articles