简体   繁体   中英

How to add attributes to a base class's properties

I have a couple model classes like so:

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

public class MyModel : MyModelBase
{
    public string SomeOtherProperty { get; set; }
}

How can MyModel add a [Required] attribute to the Name property?

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.

eg

[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; }
}

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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