简体   繁体   English

使用反射从元数据类中获取属性属性

[英]Using reflection to get property attributes from a metadata class

I have a LINQ generated class called Project. 我有一个名为Project的LINQ生成类。

I wanted to add some attributes to the generated properties, so I defined a partial class with the MetadataType attribute. 我想为生成的属性添加一些属性,因此我使用MetadataType属性定义了一个部分类。

[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 . 但是,我只获得System.Data.Linq.Mapping.ColumnAttribute类型的一个属性。 My HiddenColumn attribute is not included in the collection. 我的HiddenColumn属性未包含在集合中。 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?) 那只用于内部框架元数据(假设这是MVC,或者可能是动态数据?)

As @CyanLite mentioned in the comments, you can use the Meta class from the metadata attribute described here (the link Cyan added). 正如@CyanLite在评论中提到的,您可以使用此处描述的元数据属性的Meta类(Cyan添加的链接)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM