Using the DefaultValueAttribute on a class that is used as the type in a MetadataTypeAttribute

StackOverflow https://stackoverflow.com/questions/4741909

  •  12-10-2019
  •  | 
  •  

Question

I've been using the MetadataType attribute to add validation attributes to classes I'm generating using a T4 template. This works wonderfully, but I'd like to be able to use the DefaultValue attribute on some properties, so that my MetadataType class will more completely describe my classes (and so that I won't have to implement the OnCreated method in those classes). I can add the attribute to my MetadataType class, but it has no effect.

Here is some example source - the generated part is (of course) in a different file. If I instantiate a Widget object, the Name property will be null.

/// <summary>
/// This part is generated
/// </summary>
public partial class Widget
{
    public string Name { get; set; }
}

/// <summary>
/// This part is hand-coded so I can add attributes, custom methods etc.
/// </summary>
[System.ComponentModel.DataAnnotations.MetadataType(typeof(WidgetMetadata))]
public partial class Widget
{
}

/// <summary>
/// This part is hand-coded, and any validation attributes I add work fine.
/// </summary>
public class WidgetMetadata
{
        [System.ComponentModel.DefaultValue("Default Name")]
        [StringLengthValidator(0, RangeBoundaryType.Inclusive, 320, RangeBoundaryType.Inclusive, Tag = "Invalid string length", MessageTemplate = "{1} must contain between \'{3}\' to \'{5}\' characters.")]
        public string Name { get; set; }
}

What am I doing wrong?, or is this not supported (and if so is it documented anywhere?)

Was it helpful?

Solution

Add a constructor to the WidgetMetaData class and set the default value of the property there. The DefaultValueAttribute is used for the Visual Studio Toolbox (I believe) to determine whether the value should be bold (changed) or not (default value), among other things. You still need to set the value of the property at some point.

public WidgetMetaData() 
{
    Name = "Default Value";
}

More information on the DefaultValueAttribute: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute(v=vs.71).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top