0

I have an entity called Doctor, in the create doctor form I added custom validation logic as follows:

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;
    }
}

and then in the Doctor model class:

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

and it works as expected when creating doctors but it also shows up in the edit form of Doctor, I know one way to remedy this is to use a viewmodel in the create form and do the validation there but that would require alot of debugging on my part as I've written alot of code depending on it being passed a Doctor model, so how do I fix that ?

4

1 回答 1

1

You can update your custom validation attribute to accept your Id property so that you can use that when you do your check against your db.

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;
    }
}

When user creates a new record, the value of DoctorId will be 0 and when editing it will be a valid doctorId value.

Now in your view model,

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

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

nameof will return a string "DoctorId"(name of that property). If your c# version does not support this keyword, simply use the string "DoctorId" as the constructor parameter.

于 2016-05-01T18:24:46.700 回答