djmj
djmj

Reputation: 5544

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!

Upvotes: 4

Views: 2301

Answers (1)

Dismissile
Dismissile

Reputation: 33071

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

Upvotes: 5

Related Questions