How to add attributes to a base class's properties

后端 未结 4 1912
独厮守ぢ
独厮守ぢ 2020-12-08 12:51

I have a couple model classes like so:

public class MyModelBase
{
    public string Name { get; set; }
}

public class MyModel : MyModelBase
{
    public str         


        
相关标签:
4条回答
  • 2020-12-08 13:23

    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.

    0 讨论(0)
  • 2020-12-08 13:27

    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; }
    }
    
    0 讨论(0)
  • 2020-12-08 13:29

    You can overload the base property by "new" keyword.

    public class MyModelBase
    {
         public string Name { get; set; }
    }
    
    public class MyModel : MyModelBase
    {
         [Required]
         public new string Name {get; set;}
         public string SomeOtherProperty { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-08 13:36

    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; }
    }
    
    0 讨论(0)
提交回复
热议问题