C#C
C#3y ago
demndev

✅ ef core can't translate a query

query:

var username = "some username";
var user = await _db.Users
            .FirstOrDefaultAsync(u => u.Username.Value == username);


UserConfiguration:

public void Configure(EntityTypeBuilder<UserEntity> builder)
    {
        builder.HasKey(u => u.Id);
        
        builder.Property(u => u.Username)
            .HasConversion(
                u => u.Value, 
                value => new Username(value));

        builder.Property(u => u.Password)
            .HasConversion(
                p => p.Value,
                value => Password.FromValue(value));
    }


Password VO:

public class Password
{
    public string Value { get; private set; }
    private readonly IPasswordHasher _passwordHasher;

    private Password(string value)
    {
        Value = value;
        _passwordHasher = null!;
    }
    
    private Password(string value, IPasswordHasher passwordHasher)
    {
        _passwordHasher = passwordHasher;
        Value = value;
    }

    public static Password Create(string value, IPasswordHasher passwordHasher)
    {
        Validate(value);

        return new(passwordHasher.GetHash(value), passwordHasher);
    }

    public static Password FromValue(string value)
    {
        return new Password(value);
    }

    public void Update(string newValue)
    {
        Validate(newValue);

        Value = _passwordHasher.GetHash(newValue);
    }
    
    private static void Validate(string value)
    {
        if (value.Length is not (<= 100 and >= 8))
            throw new Exceptions.InvalidPasswordLengthException();
    }
}
Was this page helpful?