Get MetaData Type from PropertyInfo

1.7k views Asked by At

My code below:

foreach (var PI in ObjType.GetProperties())
{
    var metaData = ModelMetadataProviders.Current.GetMetadataForType(null, PI.GetType());
    string DispName = metaData.DisplayName
}

ObjType is the type of an EF6 schema first entity with DisplayName been added as a Metadata class. The error above is probably because PI.GetType() returns the type of the PropertyInfo. But I really can't figure out how to get the property itself.

I have look into various example using:

ModelMetadata.FromLambdaExpression(expression, helper.ViewData);

However, in my case, I am not using any Lambda Expression. I just need to construct a list of the properties' DisplayName and pass it on.

2

There are 2 answers

0
Eren Ersönmez On

But I really can't figure out how to get the property itself.

You want PropertyInfo.PropertyType, so change PI.GetType() to PI.PropertyType.

0
TheRWS96 On

I don't know if this will help you, but this is how i got the MetaDataClassType from the object it has been attached to.

Example Class with a MetadataType:

[MetadataType(typeof(TheMetaDataYouWantTheTypeFrom))]
public class ObjectYouWantMetaDataTypeFrom
{
    public string Username { get; set; }
    public string Name { get; set; }
}

public class TheMetaDataYouWantTheTypeFrom
{
    [Required(ErrorMessage = "You must enter a username.")]
    public object Username { get; set; }

    [Required(ErrorMessage = "You must enter a name.")]
    public object Name { get; set; }
}

The Code to get the MetadataClassType

Type ObjectType = ObjectYouWantMetaDataTypeFrom.GetType();
object ObjectMetaData = ObjectType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();

MetadataTypeAttribute MetaData = ObjectMetaData as MetadataTypeAttribute;
if (MetaData == null)
{ throw new NullReferenceException(); }

Type metadataClassType = MetaData.MetadataClassType;