我首先开发ASP.NET MVC4应用程序,EF代码。 我有基类:
public class Entity
{
public int Id { get; set; }
public string Title { get; set; }
}
我有一些派生类,例如:
public class City : Entity
{
public int Population { get; set; }
}
还有许多其他派生类(文章,主题,汽车等)。现在我想在所有类中对Title属性实现“Required”属性,并且我希望不同的派生类有不同的ErrorMessages。例如,主题类的“标题不能为空”,“为汽车类别命名您的汽车”等。我该怎么办?谢谢!
答案 0 :(得分:11)
您可以在基类中将属性设为虚拟:
public class Entity
{
public int Id { get; set; }
public virtual string Title { get; set; }
}
然后在子类中覆盖它,使其成为必需项,并指定您希望显示的错误消息:
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; }
}
}
或者,您可以使用FluentValidation.NET
而不是数据注释来定义验证逻辑,在这种情况下,您可以为不同的具体类型使用不同的验证器。例如:
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");
}
}
...