使用反射从元数据类获取属性属性 [英] Using reflection to get property attributes from a metadata class

查看:117
本文介绍了使用反射从元数据类获取属性属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由LINQ生成的名为Project的类。

I have a LINQ generated class called Project.

我想在生成的属性中添加一些属性,因此我定义了带有MetadataType属性的局部类。 / p>

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

我只得到一个属性,类型为 System.Data.Linq .Mapping.ColumnAttribute 。我的 HiddenColumn 属性未包含在集合中。我的问题是如何使用反射获取这些元数据属性。

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.

任何帮助将不胜感激。

推荐答案

您可以使用约定方法来反映另一个类:

You can reflect the other class, using a convention approach:

var type = Type.GetType(entityType.FullName + "_HiddenProps," + entityType.AssemblyQualifiedName);
type.GetProperty("Id").GetCustomAttributes(false);

伙伴类不能自动与核心组件合并。这仅用于内部框架元数据(假设这是MVC,还是动态数据?)

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

正如评论中提到的@CyanLite,您可以使用元数据属性在此处描述(链接添加了青色)。

As @CyanLite mentioned in the comments, you can use the Meta class from the metadata attribute described here (the link Cyan added).

这篇关于使用反射从元数据类获取属性属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆