Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to get property attributes from a metadata class

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.

like image 217
Jeremy Wiggins Avatar asked Dec 18 '25 10:12

Jeremy Wiggins


1 Answers

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

like image 85
Brian Mains Avatar answered Dec 19 '25 23:12

Brian Mains



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!