У себя в проекте запилил класс, который возвращает список сущностей по отбору, сформированному на клиентской стороне (аналог отбора в 1С). Кратко суть такая: у пользователя на клиентской стороне есть форма в которой он может выбрать поля, способ сравнения и значения для фильтра данных журнала сущности. На сервере это преобразуется в список SelectionSettings (Имя таблицы (строка) Имя колонки (строка), тип колонки (строка) способ сравнения (int) и значение (строка, для списка значений строка с разделителем)). Далее, как и в предыдущих ответах используется Expression<Func<TEntity, bool>> и Reflaction
public class ExpressionParts
{
public ExpressionParts() { }
public Expression Left { get; set; }
public Expression Right { get; set; }
}
public class SelectionConditionsBuilder<TEntity> where TEntity : class
{
public SelectionConditionsBuilder() { }
public Expression<Func<TEntity, bool>> Condition(List<SelectionSettings> selection)
{
Expression condition = null;
Expression subCondition = null;
var param = Expression.Parameter(typeof(TEntity), "e");
if(selection.Count == 0)
{
condition = Expression.Constant(true);
return Expression.Lambda<Func<TEntity, bool>>(condition, param);
}
for (int i = 0; i < selection.Count; i++)
{
bool skip = false;
PropertyInfo ptopertyInfo;
if (selection[i].DataType.IndexOf(".") == -1)
ptopertyInfo = typeof(TEntity).GetProperty(selection[i].TableColumn);
else
ptopertyInfo = typeof(TEntity).GetProperty(selection[i].TableColumn + "Id");
foreach (var atr in ptopertyInfo.CustomAttributes)
{
if (atr.AttributeType.Name == "NotMappedAttribute")
{
skip = true;
break;
}
}
if (skip)
continue;
switch (selection[i].ComparisonType)
{
case ComparisonType.Equals:
subCondition = EqualExpression(selection[i], param, ptopertyInfo);
break;
case ComparisonType.NotEqual:
subCondition = NotEqualExpression(selection[i], param, ptopertyInfo);
break;
case ComparisonType.More:
subCondition = GreaterThanExpression(selection[i], param, ptopertyInfo);
break;
case ComparisonType.MoreOrEqual:
subCondition = GreaterThanOrEqualExpression(selection[i], param, ptopertyInfo);
break;
case ComparisonType.Less:
subCondition = LessThanExpression(selection[i], param, ptopertyInfo);
break;
case ComparisonType.LessOrEqual:
subCondition = LessThanOrEqualExpression(selection[i], param, ptopertyInfo);
break;
case ComparisonType.InList:
subCondition = InListExpression(selection[i], param, ptopertyInfo);
break;
case ComparisonType.NotInList:
subCondition = NotInListExpression(selection[i], param, ptopertyInfo);
break;
};
condition = (condition == null ? subCondition : Expression.AndAlso(condition, subCondition));
}
return Expression.Lambda<Func<TEntity, bool>>(condition, param);
}
public Expression GetExpressionLeftPart(ParameterExpression param, PropertyInfo info)
{
Expression left = Expression.Property(param, info.Name);
return left;
}
public Expression GetExpressionListRightPart(SelectionSettings setting, PropertyInfo info, string data)
{
Expression right = null;
switch (setting.DataType)
{
case "String":
right = Expression.Constant(data);
break;
case "Int32":
right = Expression.Constant(int.Parse(data));
break;
case "Bool":
right = Expression.Constant(bool.Parse(data));
break;
default:
if (setting.DataType.StartsWith("References."))
{
right = Expression.Constant(int.Parse(data));
break;
}
break;
}
return right;
}
public ExpressionParts GetExpressionParts(SelectionSettings setting, ParameterExpression param, PropertyInfo info, int index = -1)
{
var parts = new ExpressionParts();
parts.Left = Expression.Property(param, info.Name);
string data = setting.SerialisedData;
switch (setting.DataType)
{
case "String":
parts.Right = Expression.Constant(data);
break;
case "Int32":
parts.Right = Expression.Constant(int.Parse(data));
break;
case "Bool":
parts.Right = Expression.Constant(bool.Parse(data));
break;
default:
if (setting.DataType.StartsWith("References."))
{
parts.Right = Expression.Constant(int.Parse(data));
break;
}
break;
}
return parts;
}
public Expression EqualExpression(SelectionSettings setting, ParameterExpression param, PropertyInfo info)
{
var parts = GetExpressionParts(setting, param, info);
return Expression.Equal(parts.Left, parts.Right);
}
public Expression NotEqualExpression(SelectionSettings setting, ParameterExpression param, PropertyInfo info)
{
var parts = GetExpressionParts(setting, param, info);
return Expression.NotEqual(parts.Left, parts.Right);
}
public Expression GreaterThanExpression(SelectionSettings setting, ParameterExpression param, PropertyInfo info)
{
var parts = GetExpressionParts(setting, param, info);
return Expression.GreaterThan(parts.Left, parts.Right);
}
public Expression GreaterThanOrEqualExpression(SelectionSettings setting, ParameterExpression param, PropertyInfo info)
{
var parts = GetExpressionParts(setting, param, info);
return Expression.GreaterThanOrEqual(parts.Left, parts.Right);
}
public Expression LessThanExpression(SelectionSettings setting, ParameterExpression param, PropertyInfo info)
{
var parts = GetExpressionParts(setting, param, info);
return Expression.LessThan(parts.Left, parts.Right);
}
public Expression LessThanOrEqualExpression(SelectionSettings setting, ParameterExpression param, PropertyInfo info)
{
var parts = GetExpressionParts(setting, param, info);
return Expression.LessThanOrEqual(parts.Left, parts.Right);
}
public Expression InListExpression(SelectionSettings setting, ParameterExpression param, PropertyInfo info)
{
Expression inlist = null;
Expression left = GetExpressionLeftPart(param, info);
var data = setting.SerialisedData.Split(";");
foreach(var item in data)
{
Expression right = GetExpressionListRightPart(setting, info, item);
Expression equal = Expression.Equal(left, right);
inlist = (inlist == null ? equal : Expression.OrElse(inlist, equal));
}
return inlist;
}
public Expression NotInListExpression(SelectionSettings setting, ParameterExpression param, PropertyInfo info)
{
Expression inlist = null;
Expression left = GetExpressionLeftPart(param, info);
var data = setting.SerialisedData.Split(";");
foreach (var item in data)
{
Expression right = GetExpressionListRightPart(setting, info, item);
Expression equal = Expression.NotEqual(left, right);
inlist = (inlist == null ? equal : Expression.AndAlso(inlist, equal));
}
return inlist;
}
}
t.TypeDiscriminator
известен статически? Вы ж не хотите lookup то нему проводить на уровне базы?t => (t.TypeDiscriminator == guid1) ? new SimpleTaskDto((ISimpleTask)t) : (t.TypeDiscriminator == guid2) ? new FooTaskDto((IFooTask)t) : new TaskDto(t)
?