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!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With