Created
September 3, 2013 15:18
-
-
Save drunkcod/6425312 to your computer and use it in GitHub Desktop.
So I wanted a general enough way to get the id columns from my entities. This is either Paula Bean brilliant or glorious. I don't know which.
This file contains 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
static class EntitySupport | |
{ | |
class IdentityGetter<TEntity> | |
{ | |
public readonly static Func<TEntity,int> Instance = GetIdentityGetter<TEntity>(); | |
} | |
public static Func<TEntity,int> GetIdentityGetter<TEntity>() | |
{ | |
var id = typeof(TEntity).GetMembers() | |
.Select(member => new { member, column = (ColumnAttribute)member.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault() }) | |
.SingleOrDefault(x => x.column != null && x.column.DbType == "Int NOT NULL IDENTITY"); | |
switch(id.member.MemberType) | |
{ | |
case MemberTypes.Property: return (Func<TEntity,int>)Delegate.CreateDelegate(typeof(Func<TEntity, int>), (id.member as PropertyInfo).GetGetMethod()); | |
} | |
return _ => { throw new NotSupportedException(); }; | |
} | |
public static int GetIdentity<TEntity>(TEntity entity) | |
{ | |
return IdentityGetter<TEntity>.Instance(entity); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment