简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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