Various DataAnnotation Attributes for Derived Classes

I am developing an ASP.NET MVC4 application, first with EF code. I have a base class:

public class Entity { public int Id { get; set; } public string Title { get; set; } } 

And I have some derived classes, for example:

 public class City : Entity { public int Population { get; set; } } 

And many other derived classes (article, topic, car, etc.). Now I want to implement the “Required” attribute for the Title property in all classes and I want different ErrorMessages to exist for different derived classes. For example, “Name must not be empty” for the class “Class”, “Name your car” for the class of cars, etc. How can i do this? Thanks!

+7
c # asp.net-mvc
source share
1 answer

You can make the property virtual in the base class:

 public class Entity { public int Id { get; set; } public virtual string Title { get; set; } } 

and then override it in the child class, set it and specify the error message you want to display:

 public class City : Entity { public int Population { get; set; } [Required(ErrorMessage = "Please name your city")] public override string Title { get { return base.Title; } set { base.Title = value; } } } 

Alternatively, you can use FluentValidation.NET instead of data annotations to define your validation logic, in which case you can have different validators for different specific types. For example:

 public class CityValidator: AbstractValidator<City> { public CityValidator() { this .RuleFor(x => x.Title) .NotEmpty() .WithMessage("Please name your city"); } } public class CarValidator: AbstractValidator<Car> {  public CityValidator()  {    this      .RuleFor(x => x.Title)      .NotEmpty()      .WithMessage("You should specify a name for your car");  } } ... 
+11
source share

All Articles