アイデアをくれたBob Valeに感謝します!いくつかのモデルがあり、コードが非常に反復的であることに気付きました。この基本クラスを作成しました:
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Core.Models
{
public abstract class ValidatableObject : IDataErrorInfo
{
public virtual bool IsValid() => this[null] == null;
[NotMapped]
public string? Error => this[null];
[NotMapped]
protected abstract (string, Func<string?>)[] Checks { get; }
public virtual string? this[string? name] => validate(name, Checks);
private static string? validate(string? name, params (string, Func<string?>)[] checks)
{
StringBuilder results = new();
foreach ((string val, Func<string?> check) in checks)
{
if (String.IsNullOrEmpty(name) || name == val)
{
string? result = check();
if (result != null)
results.AppendLine(result);
}
}
return results.Length == 0
? null
: results.ToString(0, results.Length - Environment.NewLine.Length);
}
}
}
そして、ここに使用法があります:
private class Validatable : ValidatableObject
{
public string Email { get; set; }
public string Comment { get; set; }
protected override (string, Func<string?>)[] Checks => new (string, Func<string?>)[]
{
(nameof(Email), () => Validate.Email(Email)),
(nameof(Comment), () => Validate.LengthOfOptionalString(Comment)),
};
}