Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public static Expression<Func<TEntity, TDto>> CreateExpression<TEntity, TDto>()
where TEntity : IEntity
where TDto : IEntityDto<TEntity>
{
var parameter = Expression.Parameter(typeof(TEntity), "t");
Type parameterType = typeof(TEntity);
Type dtoType = registeredDto[parameterType];
// new ctor(t)
Expression result = Expression.New(dtoType.GetConstructor(new[] { parameterType }), parameter);
// t.TypeDiscriminator
var typeDiscr = Expression.Property(parameter, typeof(IEntity).GetProperty("TypeDiscriminator"));
var childs = registeredDto.Where(v => parameterType != v.Key && parameterType.IsAssignableFrom(v.Key)).ToList();
foreach (var child in childs)
{
// параметры конкретной итерации цикла
parameterType = child.Key;
dtoType = child.Value;
var guid = parameterType.GetTypeGuid().GetOriginalTypeGuid();
// t.TypeDiscriminator == guid1
var test = Expression.Equal(typeDiscr, Expression.Constant(guid));
// (ISimpleTask)t
var parameterCasted = Expression.Convert(parameter, parameterType);
// new SimpleTaskDto((ISimpleTask)t)
var altResult = Expression.New(dtoType.GetConstructor(new[] { parameterType }), parameterCasted);
var downcasted = Expression.Convert(altResult, typeof(TDto));
// аккумулированный результат
result = Expression.Condition(test: test, ifTrue: downcasted, ifFalse: result);
}
// собираем всё в лямбду:
return Expression.Lambda<Func<TEntity, TDto>>(result, parameter);
}
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.