この問題を間違った方法で解決しようとしている可能性があります。つまり、オブジェクト(つまり、引数、エンティティなど)を操作(挿入、更新、選択など)で検証する必要があります。C#検証パターン - 特定の操作でエンティティを検証するためのベストプラクティス
ここでは、1つのクラスと2つの操作に対してのみ小さなコードサンプルを作成しました。しかし、私の実際のプロジェクトでは、Personや操作のような多くのクラスがあります。
Person.cs
public class Person
{
public int Id {get;set;}
public string Name {get;set;}
public DateTime Birthdate {get;set;}
public BeverageSelectionType BeverageSelection {get;set;}
}
BeverageSelectionType.cs
public enum BeverageSelectionType
{
NotSet,
Juice,
Beer,
Water
}
IService.cs
public interface IService
{
void Update(Person person);
Person Add(Person person);
}
PersonSevice.cs(私はservice
として選んだのが、で、それをシンプルに説明するために現実私はrepository pattern
とUnitOfWork
を使っていますHTここに書くのは長いだろう)
public class PersonService : IService
{
public void Update(Person person)
{
if(person.BeverageSelection == BeverageSelectionType.NotSet
|| (person.BeverageSelection == BeverageSelectionType.Beer && person.Birthdate < DateTime.Now.AddYears(-18))
)
throw new MyInvalidException("Parameters NOT valid for UPDATE operation");
//Do update with expected parameters
}
public Person Add(Person person)
{
if(person.Birthdate <= DateTime.MinValue || person.Birthdate >= DateTime.MaxValue)
throw new MyInvalidException("Parameters NOT valid for ADD operation");
//Do add with expected parameters
}
}
私が操作に対する実体を検証するのに役立ちます検証のための可能なアプローチとして、一般的なようなを設計する必要があります。私は各サービスにバリデーションロジックを追加したくないだけです。
Person.cs
public class Person
{
public int Id {get;set;}
public string Name {get;set;}
public DateTime Birthdate {get;set;}
public BeverageSelectionType BeverageSelection {get;set;}
public bool IsValid(ModelValidationType modelValidationType)
{
switch(modelValidationType)
{
case ModelValidationType.Update:
if(person.BeverageSelection == BeverageSelectionType.NotSet
|| (person.BeverageSelection == BeverageSelectionType.Beer && person.Birthdate < DateTime.Now.AddYears(-18))
)
return false;
case ModelValidationType.Add:
if(person.Birthdate <= DateTime.MinValue || person.Birthdate >= DateTime.MaxValue)
return false;
}
return true;
}
}
:ここ はすべてのエンティティは、それが有効ですが、私も有用であったが、まだ十分ではないと信じてどのようにときと自体を知っていることを別のアプローチであります
最も適切なバリデーション手法をどのように実装しますか?
ありがとうございます。
ありがとうございます。私はすぐに詳細を確認します。 –
もちろん、歓迎です:) – Andre