Search code examples
.netlinqentity-framework-core

EF Core 8 : single value objects. Error on linq


In EF Core 8, I'm trying to do this query (Active is a simple value object of type bool):

return await _dbSet
                .Where(e => e.Active.Value)
                .ToListAsync();

And I get:

The LINQ expression 'DbSet()\r\n .Where(e => e.Active.Value)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information."

Entity:

public abstract class StarSchemaEntity : Entity
{
    public Date Timestamp { get; set; } = new Date(DateTime.Now);
    public DatabaseBoolean Active { get; set; } = new DatabaseBoolean(true);
}


public partial class ExecutionEntity : StarSchemaEntity
{ 
    public Name Name { get; set; } = null!;
}

ModelBuilder:

modelBuilder.Entity<ExecutionEntity>(entity =>
{
    entity.HasKey(e => e.Id);

    entity.ToTable("EXECUTIONS");

    entity.Property(e => e.Id)
        .HasConversion<DatabaseTableIdConverter>()
        .HasColumnType("NUMBER")
        .HasColumnName("Id");
    entity.Property(e => e.Active)
        .HasConversion<DatabaseBooleanConverter>()
        .HasMaxLength(1)
        .IsUnicode(false)
        .HasDefaultValueSql("'Y'")
        .IsFixedLength()
        .HasColumnName("ACTIVE");
    entity.Property(e => e.Name)
        .HasConversion<NameConverter>()
        .HasMaxLength(50)
        .IsUnicode(false)
        .HasColumnName("NAME");
    entity.Property(e => e.Timestamp)
        .HasConversion<DateConverter>()
        .HasPrecision(6)
        .HasDefaultValueSql("CURRENT_TIMESTAMP ")
        .HasColumnName("TIMESTAMP");
}); 

Converter:

public class DatabaseBooleanConverter : ValueConverter<DatabaseBoolean, string>
{
    public DatabaseBooleanConverter() : base
    (
        v => v.Value.ToString(),
        v => new DatabaseBoolean(v, true))
    { }
}

How could I do a linq operation using value objects?


Solution

  • Linq does not allow conversions.

    To solve the error instead of comparing a value object value with a primitive value I compared the value object against a value object

    var TrueValue = new DatabaseBoolean(true);
    return await _dbSet
        .Where(e => (e.Active == TrueValue))
        .ToListAsync();
    

    This solved the error