frenchie
frenchie

Reputation: 52027

handling a null in linq to sql query

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.

Upvotes: 1

Views: 2313

Answers (2)

BrokenGlass
BrokenGlass

Reputation: 160992

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();

Upvotes: 1

Anthony Pegram
Anthony Pegram

Reputation: 126952

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.

Upvotes: 1

Related Questions