[英]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. ObjType
是ObjType
架构第一个实体的类型,其中DisplayName
已添加为Metadata
类。 The error above is probably because PI.GetType()
returns the type of the PropertyInfo
. 上面的错误可能是因为
PI.GetType()
返回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. 但是,就我而言,我没有使用任何Lambda表达式。 I just need to construct a list of the properties'
DisplayName
and pass it on. 我只需要构造属性的
DisplayName
的列表并将其传递。
But I really can't figure out how to get the property itself.
但是我真的不知道如何获得财产本身。
You want PropertyInfo.PropertyType , so change PI.GetType()
to PI.PropertyType
. 您需要PropertyInfo.PropertyType ,因此将
PI.GetType()
更改为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. 我不知道这是否对您有帮助,但这是我从已附加对象的MetaDataClassType中获取信息的方法。
Example Class with a MetadataType: 具有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 获取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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.