Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different DataAnnotation attributes for derived classes

Tags:

c#

asp.net-mvc

I develop ASP.NET MVC4 app, EF Code first. I have 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 "Required" attribute to Title property in all classes and i want there are different ErrorMessages for different derived classes. For example, "Title must not be empty" for Topic class, "Please name your car" for Car class etc. How can i do this? Thanks!

like image 998
ifeelgood Avatar asked Aug 21 '13 17:08

ifeelgood


1 Answers

You could 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, make it required and specify the error message that you would like to be displayed:

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 could use FluentValidation.NET instead of data annotations to define your validation logic and in this case you could have different validators for the different concrete 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");
    }
}

...
like image 187
Darin Dimitrov Avatar answered Oct 06 '22 04:10

Darin Dimitrov