根据我使用Automapper映射Linq.Expression的测试,不支持在不同的命名空间中使用“Enum”。 请参阅下面的示例,
namespace TestNamespace1
{
public enum EnumTypes
{
EnumType01,
EnumType02
}
}
namespace TestNamespace2
{
public enum EnumTypes
{
EnumType01,
EnumType02
}
}
namespace MappingTest
{
class A
{
public TestNamespace1.EnumTypes EnumType { get; set; }
}
class B
{
public TestNamespace2.EnumTypes EnumType { get; set; }
}
class TestMapping
{
static void Main()
{
var bDataSource = new List<B> { new B { EnumType = **TestNamespace2**.EnumTypes.EnumType01 } };
Mapper.CreateMap<A, B>();
Mapper.CreateMap<B, A>();
Expression<Func<A, bool>> expressionA = x => x.EnumType == TestNamespace1.EnumTypes.EnumType01;
var expressionB = GetMappedSelectorForAB(expressionA);
var result = bDataSource.AsQueryable().Where(expressionB);
foreach (B b in result)
{
Console.WriteLine("Matching B: {0}", b.EnumType.ToString());
}
}
static Expression<Func<B, bool>> GetMappedSelectorForAB(Expression<Func<A, bool>> selector)
{
Expression<Func<B, A>> mapper = AutoMapper.QueryableExtensions.Extensions.CreateMapExpression<B, A>(Mapper.Engine);
Expression<Func<B, bool>> mappedSelector = selector.Compose(mapper);
return mappedSelector;
}
}
public static class FunctionCompositionExtensions
{
public static Expression<Func<X, Y>> Compose<X, Y, Z>(this Expression<Func<Z, Y>> outer, Expression<Func<X, Z>> inner)
{
return Expression.Lambda<Func<X, Y>>(
ParameterReplacer.Replace(outer.Body, outer.Parameters[0], inner.Body),
inner.Parameters[0]);
}
}
class ParameterReplacer : ExpressionVisitor
{
private ParameterExpression _parameter;
private Expression _replacement;
private ParameterReplacer(ParameterExpression parameter, Expression replacement)
{
_parameter = parameter;
_replacement = replacement;
}
public static Expression Replace(Expression expression, ParameterExpression parameter, Expression replacement)
{
return new ParameterReplacer(parameter, replacement).Visit(expression);
}
protected override Expression VisitParameter(ParameterExpression parameter)
{
if (parameter == _parameter)
{
return _replacement;
}
return base.VisitParameter(parameter);
}
}
}
AutoMapper.QueryableExtensions.Extensions.CreateMapExpression
我已经看到了Automapper的源代码,并对其进行了调试我将收到此错误“无法从...创建地图表达式”
如果A类和B类都使用来自同一名称空间的相同Enum,那么它可以正常工作
class A
{
public TestNamespace1.EnumTypes EnumType { get; set; }
}
class B
{
public TestNamespace1.EnumTypes EnumType { get; set; }
}
有没有办法实现它?我们知道目标和源对象可能有自己的名称空间[DTO]。