Skip to main content

How to not return all properties in SqlRaw

8/11/2025
1 minute read

Entity Frameworks SqlRaw has a small, sometimes annoying limitation:

The SQL query must return data for all properties of the entity type.

Sometimes that isn't desirable, so let's overcome that super easy.

The limitation#

Imagine you have an object like this:

csharp
public sealed record MyEntity
{
    public double? PropA { get; init; }
    public double? PropB { get; init; }
}

Basically, we express that either PropA or PropB are optional and therefore if not present in the result set, should be null. But SqlRaw expects all properties in an entity present in the SELECT clause.

So:

csharp
dbContext
    .Database
    .SqlQuery<MyEntity>($"SELECT PropA FROM MyTable")
    .ToListAsync(token);

Will fail with an exception that EF can't map the query to the type as there is PropB missing.

To simply overcome this, return PropB explicitly as NULL:

csharp
dbContext
    .Database
    .SqlQuery<MyEntity>($"SELECT PropA, NULL AS PropB FROM MyTable")
    .ToListAsync(token);

Tada, EF is happy again. Of course that is an oversimplified example, but you get the idea.

An error has occurred. This application may no longer respond until reloaded.Reload x