I'm new to the EF Core world, a simple query like this one:
return await DbContext
.Set<Customer>()
.AnyAsync(c => c.Email.Value == email, cancellationToken);
throws this error:
The LINQ expression 'DbSet() .Any(c => c.Email.Value == __email_0)' could not be translated.
Configuration for the Email in the database model:
builder.Property(customer => customer.Email)
.HasMaxLength(400)
.HasConversion(email => email.Value, value => new Domain.Customers.Email(value));
It's because EF Core cannot translate the expression c.Email.Value
into SQL.
This is a common issue when dealing with non-primitive types in the EF.
One possible solution is to change the string value to the record/complex type when comparing.
Change:
return await DbContext
.Set<Customer>()
.AnyAsync(c => c.Email.Value == email, cancellationToken);
to this
return await DbContext
.Set<Customer>()
.AnyAsync(c => c.Email == new Domain.Customers.Email(email), cancellationToken);