Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Custom Attributes applied to generated entities via MetadataType attribute

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
{
}

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

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.

Any help or pointers would save a soul.

like image 815
Dipin Behl Avatar asked Jun 20 '12 07:06

Dipin Behl


1 Answers

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.

like image 161
Ladislav Mrnka Avatar answered Nov 07 '22 16:11

Ladislav Mrnka