Skip to content

Instantly share code, notes, and snippets.

@drunkcod
Created September 3, 2013 15:18
Show Gist options
  • Save drunkcod/6425312 to your computer and use it in GitHub Desktop.
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.
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