简体   繁体   中英

Get MetaData Type from PropertyInfo

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.

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

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

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;

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