如何获取元数据自定义属性?
我有一个在类级别定义数据注释的类。元数据类具有与之关联的自定义属性,以及通常的DisplayName,DisplayFormat等。
I have a class that defines data annotations at class level. The meta data class has custom attributes associated with it, along with the usual DisplayName, DisplayFormat etc.
public class BaseMetaData
{
[DisplayName("Id")]
public object Id { get; set; }
[DisplayName("Selected")]
[ExportItem(Exclude = true)]
public object Selected { get; set; }
}
[MetadataType(typeof(BaseMetaData))]
public class BaseViewModel
{
public int Id { get; set; }
public bool Selected { get; set; }
给出类型 T ,如何从中检索自定义属性元数据类?下面的尝试不起作用,因为元数据属性来自 BaseViewModel ,而不是来自 BaseMetaData 类。
Given a type T, how can I retrieve the custom attributes from the meta data class? The attempt below would not work as the metadata properties are from the BaseViewModel rather than the BaseMetaData class.
需要可以正常工作,即不能执行typeof(BaseMetaData).GetProperty(e.PropertyName)。想知道是否存在一种从类中获取MetadataType的方法,那么它将使其成为可能。
Needs to work generically i.e. can't do typeof(BaseMetaData).GetProperty(e.PropertyName). Wondering if there is a way of getting the MetadataType from the class then it would make it possible.
var type = typeof (T);
var metaData = ModelMetadataProviders.Current.GetMetadataForType(null, type);
var propertMetaData = metaData.Properties
.Where(e =>
{
var attribute = type.GetProperty(e.PropertyName)
.GetCustomAttributes(typeof(ExportItemAttribute), false)
.FirstOrDefault() as ExportItemAttribute;
return attribute == null || !attribute.Exclude;
})
.ToList();
通过使用MetadataTypeAttribute的类型获取解决方案
Found a solution by using the type of MetadataTypeAttribute to get the custom attributes.
var type = typeof (T);
var metadataType = type.GetCustomAttributes(typeof(MetadataTypeAttribute), true)
.OfType<MetadataTypeAttribute>().FirstOrDefault();
var metaData = (metadataType != null)
? ModelMetadataProviders.Current.GetMetadataForType(null, metadataType.MetadataClassType)
: ModelMetadataProviders.Current.GetMetadataForType(null, type);
var propertMetaData = metaData.Properties
.Where(e =>
{
var attribute = metaData.ModelType.GetProperty(e.PropertyName)
.GetCustomAttributes(typeof(ExportItemAttribute), false)
.FirstOrDefault() as ExportItemAttribute;
return attribute == null || !attribute.Exclude;
})
.ToList();