【发布时间】:2016-11-15 22:44:41
【问题描述】:
我有一个带有 Nullable DateTime 属性的 PersonDTO 类:
public class PersonDTO
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
// YYYYMMDD format
public virtual Nullable<int> Birthday { get; set; }
}
以及表示层中的一个类:
public class PersonViewModel
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual Nullable<DateTime> Birthday { get; set; }
}
在我的表单上,我有两个方法负责创建 Expression<Func<PersonViewModel, bool>> 对象:
private Expression<Func<PersonViewModel, bool>> GetFilterExpression()
{
Expression condition = null;
ParameterExpression pePerson = Expression.Parameter(typeof(PersonViewModel), "person");
//...
if (dtpBirth.Format != DateTimePickerFormat.Custom)
{
Expression target = Expression.Property(pePerson, pePerson.Type.GetProperty("Birthday", typeof(DateTime?)));
UnaryExpression date = Expression.Convert(Expression.Constant(dtpBirth.Value.Date), typeof (DateTime?));
condition = (condition == null)
? Expression.GreaterThan(target, date)
: Expression.And(condition, Expression.GreaterThan(target, date));
}
// Формируем лямбду с условием и возвращаем результат сформированного фильтра
return condition != null ? Expression.Lambda<Func<PersonViewModel, bool>>(condition, pePerson) : null;
}
我也在使用 AutoMapper?它将一个Expression<Func<PersonViewModel, bool>> 转换为Expression<Func<PersonDTO, bool>>。转换代码如下:
// ...
Mapper.CreateMap<PersonViewModel, PersonDTO>()
.ForMember(dto => dto.Birthday, opt => opt.MapFrom(model => model.BirthdaySingle.NullDateTimeToNullInt("yyyyMMdd")));
// ...
public static class DataTypesExtensions
{
public static DateTime? NullIntToNullDateTime(this int? input, string format)
{
if (input.HasValue)
{
DateTime result;
if (DateTime.TryParseExact(input.Value.ToString(), format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
return result;
}
}
return null;
}
//...
}
我的表达式转换器看起来像:
public static Expression<Func<TDestination, TResult>> RemapForType<TSource, TDestination, TResult>(
this Expression<Func<TSource, TResult>> expression)
{
var newParameter = Expression.Parameter(typeof(TDestination));
var visitor = new AutoMapVisitor<TSource, TDestination>(newParameter);
var remappedBody = visitor.Visit(expression.Body);
if (remappedBody == null)
{
throw new InvalidOperationException("Unable to remap expression");
}
return Expression.Lambda<Func<TDestination, TResult>>(remappedBody, newParameter);
}
public class AutoMapVisitor<TSource, TDestination> : ExpressionVisitor
{
private readonly ParameterExpression _newParameter;
private readonly TypeMap _typeMap = Mapper.FindTypeMapFor<TSource, TDestination>();
public AutoMapVisitor(ParameterExpression newParameter)
{
_newParameter = newParameter;
}
protected override Expression VisitMember(MemberExpression node)
{
var propertyMaps = _typeMap.GetPropertyMaps();
// Find any mapping for this member
// Here I think is a problem, because if it comes (person.Birthday => Convert(16.11.2016 00:00:00)) it can't find it.
var propertyMap = propertyMaps.SingleOrDefault(map => map.SourceMember == node.Member);
if (propertyMap == null)
{
return base.VisitMember(node);
}
var destinationProperty = propertyMap.DestinationProperty;
var destinationMember = destinationProperty.MemberInfo;
// Check the new member is a property too
var property = destinationMember as PropertyInfo;
if (property == null)
{
return base.VisitMember(node);
}
// Access the new property
var newPropertyAccess = Expression.Property(_newParameter, property);
return base.VisitMember(newPropertyAccess);
}
}
我需要以某种方式将 lambda 表达式的一部分:person => person.Birthday > Convert(15.11.2016 00:00)(在这种情况下,人是 PersonViewModel 和 DateTime 类型的生日?)看起来像:person => person.Birthday > 20161115(在这种情况下,人是 PersonDTO 和生日类型诠释?)。如果没有这个问题,一切都会映射并正常工作。我知道我需要更深入地了解树并进行一些操作,但我不明白我应该如何以及在哪里执行此操作。
【问题讨论】:
-
哇。你能把代码变小,但它仍然会重现问题吗?
-
@Thomas 是的,我还没有找到答案。在 Visitor 方法中,SingleOrDefault 方法一无所获,因此转换没有按预期进行。
-
@ThomasWeller 我已经编辑了我的问题
标签: c# expression-trees