通过MetadataType属性获取应用于生成实体的自定义属性 [英] Get Custom Attributes applied to generated entities via MetadataType attribute

查看:139
本文介绍了通过MetadataType属性获取应用于生成实体的自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的应用程序中,我们使用EF4.0和POCO Entity生成器从数据库生成实体。要应用数据注释,我们正在创建接口并在我们创建的部分类上实现这些接口,以匹配使用EF生成的部分类。

In our application, we are using EF4.0 and POCO Entity generator to generate Entities from the database. To apply data annotation, we are creating Interfaces and implementing those interfaces on the partial classes we have created to match the partial class generated by using EF.

/*Entity Generated Type*/
public partial class SomeEntity : EntityBase
{
    public virtual string SomeProperty
    {
        get {...}
        set {...}
    }
}

/*Interface containing metadata*/
public interface ISomeEntityMetadata
{
    [SomeCustomAttribute]
    string SomeProperty { get; set; }
}

/*Partial matching class for interface*/
[MetadataType(typeof(ISomeEntityMetadata))]
public partial class SomeEntity : ISomeEntityMetadata
{
}

现在,使用反射,当我们尝试得到'SomeCustomAttribute'是应用于SomeEntity.SomeProperty,它返回不应用该属性。

Now, using reflection, when we try to get if 'SomeCustomAttribute' is applied on 'SomeEntity.SomeProperty', it returns that the attribute is not applied.

如果我们编辑生成的代码并直接应用属性,它将工作。

如果我们检查部分类合并形成单个类型,它确实如此。

如果我们检查要应用于类型(使用反射)的MetadataType属性,则为。

此外,当实体绑定到任何WPF的UI - 元素,验证工作正常,但使用反射,我们无法找到属性上应用的验证属性和/或自定义属性。

If we edit the generated code and apply the Attribute directly, it works.
If we check for the partial classes merging to form a single type, it does.
If we check for the MetadataType attribute to be applied on the type (using reflection), it is.
Also, when the entity is bound to any WPF's UI-Element, the validations work as they should but using reflection we are unable to find the Validation Attributes and/or Custom Attributes applied on the property.

任何帮助或指针将

推荐答案

但是标有 MetadataType 属性的接口/类将永远不会将这些属性添加到您的原始类中,因此您无法通过反射在类中找到它们。这不是 MetadataType 属性的目的。如果要使用反射,您必须首先找到 MetadataType 属性,检查传递给该属性的类型,并搜索该类型的自定义属性。这就是验证如何使用 MetadataType

But interface / class marked with MetadataType attribute will never add those attributes to your original class so you can never find them on the class with reflection. That is not a purpose of MetadataType attribute. If you want to use reflection you must first find MetadataType attribute, check the type passed to that attribute and search for your custom attribute in that type. That is how validation uses MetadataType.

这篇关于通过MetadataType属性获取应用于生成实体的自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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