Using reflection to get property attributes from a metadata class
I have a LINQ generated class called Project.
I wanted to add some attributes to the generated properties, so I defined a partial class with the MetadataType attribute.
[MetadataType(typeof(Project_HiddenProps))]
pu开发者_运维技巧blic partial class Project : IProject
{
// There are also a few additional properties defined here.
}
public class Project_HiddenProps
{
[HiddenColumn]
public System.Guid Id { get; set; }
// Id is an auto-generated property that I've added a custom attribute to
}
Later, I use reflection to try to get the attributes of this property.
var customAttributes = prop.GetCustomAttributes(false);
I only get one attribute, though, of type System.Data.Linq.Mapping.ColumnAttribute
. My HiddenColumn
attribute is not included in the collection. My question is how to get at these metadata properties using reflection.
Any help would be greatly appreciated.
You can reflect the other class, using a convention approach:
var type = Type.GetType(entityType.FullName + "_HiddenProps," + entityType.AssemblyQualifiedName);
type.GetProperty("Id").GetCustomAttributes(false);
The buddy class cannot be automatically merged with the core component. That is only used for internal framework metadata (assume this is MVC, or maybe dynamic data?)
As @CyanLite mentioned in the comments, you can use the Meta class from the metadata attribute described here (the link Cyan added).
精彩评论