我希望使用密码 struct ,而不是使用名为PasswordHash
和PasswordSalt
的两个属性(我仍然希望将它们作为USERS表上的列).但我似乎找不到一种用EF Core实现它的方法.
public class User
{
/* other properties */
public Password Password { get; set; }
}
public readonly struct Password
: IEquatable<Password>
{
public string Hash { get; }
public string Salt { get; }
public Password(string hash, string salt)
{
Hash = hash;
Salt = salt;
}
public bool Equals(Password other)
{
return Hash == other.Hash && Salt == other.Salt;
}
public override bool Equals(object? obj)
{
return obj is Password other && Equals(other);
}
public override int GetHashCode()
{
return HashCode.Combine(Hash, Salt);
}
public static bool operator ==(Password left, Password right) => left.Equals(right);
public static bool operator !=(Password left, Password right) => !left.Equals(right);
}
我知道,如果我这样做,它会奏效:
public record Password(string Hash, string Salt);
但是,我希望它使用readonly
个属性.其 idea 是,在更新密码时,您必须同时更改散列和SALT.它不是为了安全,而是为了抽象和更干净的代码.
我试着用OwnsOne
的方法.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>(entity =>
{
entity.OwnsOne(navigationExpression: u => u.Password, buildAction: navigationBuilder =>
{
navigationBuilder.Property(p => p.Salt).HasColumnName("PasswordSalt");
navigationBuilder.Property(p => p.Hash).HasColumnName("PasswordHash");
});
});
base.OnModelCreating(modelBuilder);
}