Last active
November 19, 2015 06:38
-
-
Save vbjay/1efe7e6dfe498661f42c to your computer and use it in GitHub Desktop.
Get attribute from a MemberInfo or MetadataType class used for the class the MemberInfo is defined in. This is usefull for Entity Framework Model classes and being able to pull out attributes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Imports System.ComponentModel.DataAnnotations | |
Imports System.Reflection | |
Imports System.Runtime.CompilerServices | |
Module Extensions | |
<Extension> | |
Public Function GetAttribute(Of T As Type)(MI As MemberInfo, AttType As T, Optional Inherit As Boolean = True) As Attribute | |
Dim Attrs As Attribute() = MI.GetCustomAttributes(AttType, Inherit) | |
If Attrs.Count > 0 Then | |
Return Attrs(0) | |
End If | |
Attrs = MI.DeclaringType.GetCustomAttributes(GetType(MetadataTypeAttribute), True) | |
Dim metaAttr As MetadataTypeAttribute = If(Attrs.Count < 1, CType(Nothing, MetadataTypeAttribute), TryCast(Attrs(0), MetadataTypeAttribute)) | |
Dim metaProps As MemberInfo() = If(metaAttr IsNot Nothing, metaAttr.MetadataClassType.GetMember(MI.Name), CType(Nothing, MemberInfo())) | |
If metaProps.Count = 0 Then | |
Return Nothing | |
End If | |
Attrs = metaProps(0).GetCustomAttributes(AttType, True) | |
If Attrs.Length < 1 Then | |
Return Nothing | |
End If | |
Return Attrs(0) | |
End Function | |
End Module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment