How to add attributes to a base class's properties
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; }
}
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
.
I note that none of these answers actually call the base Name property correctly. The override should write something like the following, in order that you don't have a separate value for the new property.
public class MyModelBase
{
public virtual string Name { get; set; }
}
public class MyModel : MyModelBase
{
[Required]
public override string Name { get { return base.Name; } set { base.Name = value; }
public string SomeOtherProperty { get; set; }
}