Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.