简体   繁体   English

派生类的不同DataAnnotation属性

[英]Different DataAnnotation attributes for derived classes

I develop ASP.NET MVC4 app, EF Code first. 我首先开发ASP.NET MVC4应用程序,EF代码。 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. 现在我想在所有类中对Title属性实现“Required”属性,并且我希望不同的派生类有不同的ErrorMessages。 For example, "Title must not be empty" for Topic class, "Please name your car" for Car class etc. How can i do this? 例如,主题类的“标题不能为空”,“为汽车类别命名您的汽车”等。我该怎么办? Thanks! 谢谢!

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. 或者,您可以使用FluentValidation.NET而不是数据注释来定义验证逻辑,在这种情况下,您可以为不同的具体类型使用不同的验证器。 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");
    }
}

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM