Skip to content

Instantly share code, notes, and snippets.

@xmedeko
Created March 20, 2016 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xmedeko/a0a0fed5365c3ffc93db to your computer and use it in GitHub Desktop.
Save xmedeko/a0a0fed5365c3ffc93db to your computer and use it in GitHub Desktop.
Hack to get select columns for Dapper.Contrib ORM type
namespace Helpers
{
public static class DapperSelectColumns
{
/// <summary>
/// Hack to string for select statement for the given ORM type.
/// </summary>
/// <param name="ormType"></param>
public static string SelectClause(Type ormType, string alias)
{
return GenerateSelectClause(alias, ColumnsForType(ormType));
}
/// <summary>
/// Hack to get ORM type columns for the exact select clause.
/// </summary>
/// <param name="ormType"></param>
public static string[] ColumnsForType(Type ormType)
{
var allProperties = InvokeSqlMapperExtensionsPropertiesCache("TypePropertiesCache", ormType);
var keyProperties = InvokeSqlMapperExtensionsPropertiesCache("KeyPropertiesCache", ormType);
var computedProperties = InvokeSqlMapperExtensionsPropertiesCache("ComputedPropertiesCache", ormType);
var allPropertiesExceptKeyAndComputed = allProperties.Except(keyProperties.Union(computedProperties)).ToList();
return keyProperties.Union(allPropertiesExceptKeyAndComputed).Select(p => p.Name.ToLowerInvariant()).ToArray();
}
/// <summary>
/// Generate for select statement from the given list of columns.
/// </summary>
/// <param name="alias">Table alias.</param>
/// <param name="columns">Columns names.</param>
public static string GenerateSelectClause(string alias, params string[] columns)
{
if (string.IsNullOrEmpty(alias))
alias = "";
else
alias = alias + ".";
return string.Join(", ", columns.Select(c => alias + c));
}
private static List<PropertyInfo> InvokeSqlMapperExtensionsPropertiesCache(string method, params object[] parameters)
{
return (List<PropertyInfo>)InvokePrivateStatic(typeof(SqlMapperExtensions), method, parameters);
}
public static object InvokePrivateStatic(Type type, string method, params object[] parameters)
{
return type.GetMethod(method, BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, parameters);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment