Nhibernate Valibatorの使用
-
27-10-2019 - |
質問
従業員エンティティクラスのプロパティとして使用される値オブジェクトクラス、FullNameを持っているとします。フルネームには、中央の初期、ニックネームなどがあります。しかし、ドメインの観点からは、FullNameのFirstNameとLastNameの両方のプロパティが評価されていることのみを強制したいと思います。
属性とは対照的に、これをEmployeevalidator:validationDef {Employee}オブジェクトの一部として表現したい。
まず、FullName(つまり、FirstAndlastnameRequed)用のクラスバリデーターを作成し、従業員のFullNameプロパティが有効であると言う必要がありますか(Lovasious Form of ValidAttributeを使用)。
余談ですが、そうです このドキュメント まだ最高ですが、3歳の時代遅れに見えます。私が逃した新しいものはありますか?
乾杯、
ベリー
アップデート
私はまだこれを理解していませんが、ここでnhibバリデーター情報の最良のソースである可能性が高いものを見つけました。 http://fabiomaulo.blogspot.com/search/label/validator
質問をよりよく表現するためのいくつかのpsuedoコードがあります:
/// <summary>A person's name.</summary>
public class FullName
{
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string MiddleName { get; set; }
public virtual string NickName { get; set; }
}
public class EmployeeValidator : ValidationDef<Employee>
{
public EmployeeValidator()
{
Define(x => x.FullName).FirstAndLastNameRequired(); // how to get here!!
}
}
デビッドの更新
public class FullNameValidator : ValidationDef<FullName>
{
public FullNameValidator() {
Define(n => n.FirstName).NotNullable().And.NotEmpty().And.MaxLength(25);
Define(n => n.LastName).NotNullable().And.NotEmpty().And.MaxLength(35);
// not really necessary but cool that you can do this
ValidateInstance
.By(
(name, context) => !name.FirstName.IsNullOrEmptyAfterTrim() && !name.LastName.IsNullOrEmptyAfterTrim())
.WithMessage("Both a First and Last Name are required");
}
}
public class EmployeeValidator : ValidationDef<Employee>
{
public EmployeeValidator()
{
Define(x => x.FullName).IsValid(); // *** doesn't compile !!!
}
}
解決
従業員を検証するときにフルネームを検証するには、次のようなことをすると思います。
public class EmployeeValidator : ValidationDef<Employee>
{
public EmployeeValidator()
{
Define(x => x.FullName).IsValid();
Define(x => x.FullName).NotNullable(); // Not sure if you need this
}
}
その後、FullName Validatorは次のようなものになります。
public class FullNameValidator : ValidationDef<FullName>
{
public EmployeeValidator()
{
Define(x => x.FirstName).NotNullable();
Define(x => x.LastName).NotNullable();
}
}
あるいは、あなたは次のようなことをすることができると思います(構文をチェックしていません):
public class EmployeeValidator: ValidationDef<Employee>
{
public EmployeeValidator() {
ValidateInstance.By((employee, context) => {
bool isValid = true;
if (string.IsNullOrEmpty(employee.FullName.FirstName)) {
isValid = false;
context.AddInvalid<Employee, string>(
"Please enter a first name.", c => c.FullName.FirstName);
} // Similar for last name
return isValid;
});
}
}
所属していません StackOverflow