frenchie
frenchie

Reputation: 52047

linq returning object even when null

I have a query that looks like this:

var TheQuery = (from t in MyDC.Table
                where....
                select new MyModel()
                {
                    Property1 = (int?)... ?? 0
                }

Sometimes, the where clause in the query returns no data to do the select. When this happens, MyModel is null. I was hoping that with the ?? 0 for every property the query would still return an object with Property1 set to 0.

How do I rewrite this so that when no data exists to fill MyModel, MyModel doesn't come back null?

Upvotes: 0

Views: 143

Answers (1)

caesay
caesay

Reputation: 17233

well if there is nothing to select, then no MyModel will be created. TheQuery will be an empty IEnumerable.

I'm not sure what is happening if you are getting a list of null objects. I'm not sure how that is possible.

You can check to see if there are results to your query like this:

var TheQuery =  from t in MyDC.Table
                where....
                select new MyModel()
                {
                    Property1 = (int?)... ?? 0
                }

var after = TheQuery.Any() ? 
            TheQuery : 
            Enumerable.Range(0, 1).Select(k => new MyModel() { Property1 = 0 });

Upvotes: 1

Related Questions