0

Doctor というエンティティがあり、Create Doctor フォームに次のようなカスタム検証ロジックを追加しました。

public class UniqueDoctorNameAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string name = value.ToString();
        HospitalEntities db = new HospitalEntities();
        int count = db.Doctors.Where(d => d.DoctorName == name).ToList().Count;
        if (count != 0)
            return new ValidationResult("A doctor already exists with that name");
        return ValidationResult.Success;
    }
}

次に、Doctor モデル クラスで次のようにします。

public class Doctor
{
    [Required]
    [Display(Name = "Name")]
    [UniqueDoctorName]
    public string DoctorName { get; set; }
}

Doctor を作成するときに期待どおりに動作しますが、Doctor の編集フォームにも表示されます。これを修正する 1 つの方法は、作成フォームでビューモデルを使用してそこで検証を行うことですが、それには多くのデバッグが必要になります。ドクターモデルに渡されることに応じて多くのコードを書いたので、どうすればそれを修正できますか?

4

1 に答える 1

1

Id プロパティを受け入れるようにカスタム検証属性を更新して、データベースに対してチェックを行うときにそれを使用できるようにすることができます。

public class UniqueDoctorNameAttribute : ValidationAttribute
{
    private readonly string _IdPropertyName;

    public UniqueDoctorNameAttribute(string IdPropertyName)
    {
        _IdPropertyName = IdPropertyName;
    }
    protected override ValidationResult IsValid(object value,
                                                      ValidationContext validationContext)
    {
        string name = value.ToString();
        var property = validationContext.ObjectType.GetProperty(_IdPropertyName);
        if (property != null)
        {
            var idValue = property.GetValue(validationContext.ObjectInstance, null);
            var db = new HospitalEntities();
            var exists = db.Doctors.Any(d => d.DoctorName == name && d.Id!=idValue);
            if (exists )
                   return new ValidationResult("A doctor already exists with that name");

            return ValidationResult.Success;
        }
        return ValidationResult.Success;
    }
}

ユーザーが新しいレコードを作成すると、DoctorId の値は 0 になり、編集すると有効な doctorId 値になります。

ビューモデルで、

public class Doctor
{
    public int DoctorId { set; get; }

    [Required]
    [Display(Name = "Name")]
    [UniqueDoctorName(nameof(DoctorId))]
    public string DoctorName { get; set; }
}

nameof文字列「DoctorId」(そのプロパティの名前)を返します。お使いの C# バージョンがこのキーワードをサポートしていない場合は、文字列 "DoctorId" をコンストラクター パラメーターとして使用してください。

于 2016-05-01T18:24:46.700 に答える