Using reflection to get property attributes from a metadata class

血红的双手。 提交于 2019-12-23 19:09:32

问题


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))]
public 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.


回答1:


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).



来源:https://stackoverflow.com/questions/7742046/using-reflection-to-get-property-attributes-from-a-metadata-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!