AutoMapper:无法将'System.Linq.Expressions.MethodCallExpressionN'类型的对象强制转换为'System.Linq.Expressions.MemberExpression'

时间:2015-06-11 11:31:01

标签: c# linq automapper

从我从这个错误中读到的,f.E。这里: Why are some object properties UnaryExpression and others MemberExpression?

当发生一个对象时,会发生这种情况,但返回一个值类型,因此CLR必须打包它,这是另一个(一元)表达式。

真正困扰我的是,以下AutoMapper-Mapping可以毫无问题地运行:

.ForMember(d => d.IndividualId, c => c.MapFrom(f => f.Individual.Id));

当Mapping-Expression有另一个表达式返回值类型时,它才起作用:

.ForMember(d =>
    d.IndividualId, c => c.MapFrom(f =>
        f.Individuals.First(d => d.Individual.Name == "Test").Id
    ));

我写这个例子只是为了表明我想做什么,所以它可能不是100%合适的?我只是无法落后,为什么第一个Expression不会导致这个异常,因为在这两种情况下都必须打包?

修改

Itvan's回答也有效,目标只是消除包装的需要。这也适用于这样的事情:

m => m.MapFrom(f =>
    f.Individuals.Where(ms => ms.Individual.Name == name)
    .Select(i => i.Individual.Id).FirstOrDefault()
)

2 个答案:

答案 0 :(得分:2)

我刚刚遇到了同样的异常,它可能是AutoMapper中的一个错误,我不确定,但我在下班后有一个解决方法。这就是我所拥有的:

class MyDto
{
    public int? StatusId;
    public int? OtherStatusId;
}
class MyModel
{
    public int StatusId; 
}

// this should work normally
.ForMember(d => d.StatusId, c => c.MapFrom(f => f.Order.StatusId));
// this causes the exception above, but I don't know why, 
// maybe because I have some quite complex mapping
.ForMember(d => d.OtherStatusId, c => c.MapFrom(f => f.Other.StatusId));

// apply a cast on the source expression make the mapping smoothly
.ForMember(d => d.OtherStatusId, c => c.MapFrom(f => (int?)f.Other.StatusId));

答案 1 :(得分:0)

我认为某些版本的AutoMapper存在此问题。我不确定最新版本是否还会发生这种情况?

但是主要问题是尚不清楚要解决的可空表达式。 AutoMapper返回像c => c.Id这样的简单值比解析像c => c.Data.Path2.Data.Path2.Where(..).Id这样的可空表达式要容易得多。解决此问题的一种方法是检查null(旧方法)... an expression tree lambda may not contain a null propagating operator

顺便说一句,如果您尝试对数据库实体使用AutoMapper,则此代码是错误的。...我建议您使用ProjectTo并发送带有列表的参数个人ID。 更多信息:http://docs.automapper.org/en/stable/Queryable-Extensions.html

相关问题