asmo asmo - 16 days ago 7
C# Question

How to retrieve Data Annotations from code? (programmatically)

I'm using

System.ComponentModel.DataAnnotations
to provide validation for my Entity Framework 4.1 project.

For example:

public class Player
{
[Required]
[MaxLength(30)]
[Display(Name = "Player Name")]
public string PlayerName { get; set; }

[MaxLength(100)]
[Display(Name = "Player Description")]
public string PlayerDescription{ get; set; }
}


I need to retrieve the
Display.Name
annotation value to show it in a message such as The chosen "Player Name" is Frank.

=================================================================================

Another example of why I could need to retrieve annotations:

var playerNameTextBox = new TextBox();
playerNameTextBox.MaxLength = GetAnnotation(myPlayer.PlayerName, MaxLength);


How can I do that?

Answer

Extension method:

public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
    var attrType = typeof(T);
    var property = instance.GetType().GetProperty(propertyName);
    return (T)property .GetCustomAttributes(attrType, false).First();
}

Code:

var name = player.GetAttributeFrom<DisplayAttribute>("PlayerDescription").Name;
var maxLength = player.GetAttributeFrom<MaxLengthAttribute>("PlayerName").Length;
Comments