"Null TypeMapping in SQL Tree" when filtering not null using Entity Framework Core 3.1.2.0

Viewed 563

This is a simplified version of the problem I'm facing.

I have this table DbSet<Report> _dbSet where Report is:

public class Report
{
    public string Name { get; set;}
    // other fields
}

Currently I'm retrieving the distinct non-null values of Name column like this:

public async Task<IEnumerable<string>> GetDistinctReportNameAsync()
{
    return = await _dbSet
        .Select(r => r.Name)
        .Where(name => name != null)
        .Distinct()
        .ToListAsync()
}

var nonNullReportNames = await GetDistinctReportNameAsync();

I want to parameterized GetDistinctReportNameAsync to retrieve distinct values of other text columns like this:

public async Task<IEnumerable<string>> GetDistinctReportTextColumnAsync(string columnName)
{
    var parameterExpr = Expression.Parameter(typeof(Report), "r");
    var expr = Expression.Property(parameterExpr, columnName);
    var lambda = Expression.Lambda(expr, parameterExpr);
    var selectPredicate = (Expression<Func<Report, string>>)lambda;

    return = await _dbSet
        .Select(selectPredicate)
        .Where(value => value != null)
        .Distinct()
        .ToListAsync()
}

But when I call GetDistinctReportTextColumnAsync on Report.Name like this:

var nonNullReportNames = await GetDistinctReportTextColumnAsync(nameof(Report.Name));

I receive this error:

{
  "ExceptionType": "InvalidOperationException",
  "Message": "Null TypeMapping in Sql Tree",
  "InnerMessage": ""
}

If I comment out this line .Where(value => value != null) in GetDistinctReportTextColumnAsync then I can get the list of Name without any problem.

Why can't I filter with != null when using an Expression I built myself, and how can I workaround this?

My environment is below:

  • Entity Framework Core 3.1.2.0
  • .Net Standard 2.1
  • Visual Studio 2019 running on Windows 10, 64 bit
  • PostgreSQL 12.4 running on Debian 8.3.0-6, 64-bit

I have seen this question, but it is about using query with string concatenation which is not related to my problem.

0 Answers
Related