How to add attributes to a base class's properties
Solution 1:
Declare the property in the parent class as virtual:
public class MyModelBase
{
public virtual string Name { get; set; }
}
public class MyModel : MyModelBase
{
[Required]
public override string Name { get; set; }
public string SomeOtherProperty { get; set; }
}
Or you could use a MetadataType to handle the validation (as long as you're talking about DataAnnotations...otherwise you're stuck with the example above):
class MyModelMetadata
{
[Required]
public string Name { get; set; }
public string SomeOtherProperty { get; set; }
}
[MetadataType(typeof(MyModelMetadata))]
public class MyModel : MyModelBase
{
public string SomeOtherProperty { get; set; }
}
Solution 2:
Try using a metadata class. It's a separate class that is referenced using attributes that lets you add data annotations to model classes indirectly.
e.g.
[MetadataType(typeof(MyModelMetadata))]
public class MyModel : MyModelBase {
... /* the current model code */
}
internal class MyModelMetadata {
[Required]
public string Name { get; set; }
}
ASP.NET MVC (including Core) offers similar support for its attributes like FromQuery
, via the ModelMetadataTypeAttribute
.