-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Description
Ask a question
So, we're not allowed to use the null-propagation operator ?. in expression trees--annoying, but I assume there's a good reason. As a result, the documentation says we have to lie using the null-forgiving operator !. to get our code translated to SQL. However, now, as far as C# is concerned, the value can't be null, even though it really can be--which means we can't use the ?? coalesce operator any more to coalesce the null value away! Is there a solution for this? If there was an EF.Functions.Coalesce() function we could use, then at least we could have a way to use COALESCE directly, but since that doesn't exist, there doesn't seem to be a clean solution to this.
Include your code
// Some entity that has an optional reference to another entity
class First {
public int Id { get; set; }
public Second? Other { get; set; }
}
// Some other entity
class Second {
public int Id { get; set; }
public string Value { get; set; }
}
// Now we try to query...
var query =
from f in context.Firsts
select new {
Id = f.Id,
Value = f.Other.Value ?? "default" // NOPE: CS0019 Operator '??' can't be applied
Value = f.Other!.Value ?? "default" // NOPE: Same as above
Value = f.Other?.Value ?? "default" // NOPE: Can't use '?.' operator
Value = f.Other != null ? f.Other.Value ? "default" // Only solution I'm aware of, but it's clunky and translates to more complicated CASE expression instead of COALESCE
};Include provider and version information
EF Core version: 6.0.27
Database provider: NPGSQL
Target framework: .NET 6.0
Operating system: Windows 10
IDE: Visual Studio 2022 17.9.3