Created
January 28, 2019 21:15
-
-
Save abelevtsov/de71df315c409038accc82485418deef to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using System.Reflection; | |
using Microsoft.Xrm.Sdk; | |
using Microsoft.Xrm.Sdk.Query; | |
namespace Microsoft.Xrm.Sdk.Ext | |
{ | |
public class ColumnSet<TEntity> where TEntity : Entity | |
{ | |
private readonly ColumnSet columnSet = new ColumnSet(); | |
public ColumnSet(params Expression<Func<TEntity, object>>[] columns) | |
{ | |
AddColumns(columns); | |
} | |
public ColumnSet(bool allColumns) | |
{ | |
columnSet.AllColumns = allColumns; | |
} | |
public static implicit operator ColumnSet(ColumnSet<TEntity> cs) | |
{ | |
return cs.columnSet; | |
} | |
public void AddColumns(params Expression<Func<TEntity, object>>[] columns) | |
{ | |
foreach (var column in columns.Select(ExtractPropertyName)) | |
{ | |
AddColumn(column); | |
} | |
} | |
public void AddColumn(Expression<Func<TEntity, object>> column) | |
{ | |
columnSet.Columns.Add(ExtractPropertyName(column)); | |
} | |
private static string ExtractPropertyName(Expression<Func<TEntity, object>> column) | |
{ | |
switch (column.Body.NodeType) | |
{ | |
case ExpressionType.MemberAccess: | |
return ((PropertyInfo)((MemberExpression)column.Body).Member).Name.ToLowerInvariant(); | |
case ExpressionType.Convert: | |
var expr = (MemberExpression)((UnaryExpression)column.Body).Operand; | |
return ((PropertyInfo)expr.Member).Name.ToLowerInvariant(); | |
default: | |
throw new NotSupportedException($"Unsupported property expression, node type: {column.Body.NodeType}"); | |
} | |
} | |
private void AddColumn(string column) | |
{ | |
columnSet.Columns.Add(column); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment