Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 - Retrieve null instead of default if query contains no rows

Entity Foo:

public int Foo { get; set; }

EF-Query:

int? barX = FOOs.GetQuery().Where(f => f.x == x).Select(f => f.bar).SingleOrDefault();

Returns default value 0 for integer if there are no rows where f.x == x but I want to return null.

How to achieve this?

0 is no clear indicator wether the result was empty or the columns value is really 0!

like image 488
djmj Avatar asked Oct 20 '25 03:10

djmj


1 Answers

Instead of doing the projection in the query you could pull back the full entity and project after:

var foo = FOOs.GetQuery().Where(f => f.x == x).SingleOrDefault();
int? barX = foo != null ? (int?)foo.bar : null;

If you are worried about fetching the whole entity then you could return an anonymous type instead of the full thing:

var foo = FOOs.GetQuery().Where(f => f.x == x).Select(new { bar = f.bar }).SingleOrDefault();
int? barX = foo != null ? (int?)foo.bar : null;

Thanks to @Flater since I did not know this was possible (just cast it in the projection):

int? barX = FOOs.GetQuery().Where(f => f.x == x).Select(f => (int?)f.bar).SingleOrDefault();
like image 85
Dismissile Avatar answered Oct 22 '25 03:10

Dismissile



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!