xavier
xavier

Reputation: 2039

Workaround for DefaultIfEmpty

I have something like this:

public enum CoolEnum
{
  Yes = 0,
  No = 1,
  Perhaps = 2,
  Maybe = 3,
  Perchance = 4,
}

and I want to do the following:

CoolEnum? enum = await this.context
                .MyTable
                .Where(x => x.Id == id)
                .Select(x => x.CoolEnum)
                .DefaultIfEmpty((CoolEnum?)null)
                .FirstAsync();

but I get the error

Processing of the LINQ expression 'DefaultIfEmpty<Nullable<CoolEnum>> (...) failed.
This may indicate either a bug or a limitation in EF Core. 

As I have seen here, it seems it's a known low priority issue.

Then I thought I could do the following:

CoolEnum enum = await this.context
                .MyTable
                .Where(x => x.Id == id)
                .Select(x => x.CoolEnum)
                .FirstAsync();

CoolEnum? nullableEnum = enum == default ? null : enum;

But this will change all my existing enums with the default value to null, and that's not what I want.

Which clean workaround can I use? I see the following options:

Neither of them seems clean. Any better idea?

Upvotes: 1

Views: 1152

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205629

You can select the nullable value (by using the regular C# cast to the corresponding nullable type) and then FirstOrDefault{Async}:

.Select(x => (CoolEnum?)x.CoolEnum)
.FirstOrDefaultAsync();

Upvotes: 4

Related Questions