Created
March 20, 2016 17:59
-
-
Save xmedeko/a0a0fed5365c3ffc93db to your computer and use it in GitHub Desktop.
Hack to get select columns for Dapper.Contrib ORM type
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
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