我今天从 AutoMapper 2.0.0 更新到 2.2.0,发现更新破坏了一些代码。在将问题发布到 automapper github 站点之前,想在这里询问一下。
我的目标类型之一像这样初始化一个集合属性:
public class PageOf<TModel>
{
public PageOf()
{
Items = Enumerable.Empty<TModel>();
}
public IEnumerable<TModel> Items { get; set; }
}
对于 automapper 2.0.0,这很好。当我更新到 2.2.0 时,映射到此目标类型导致 NotSupportedException 出现消息“集合大小固定”。 (该异常包含在 AutoMapperMappingException 中。)
我能够通过将上面的构造函数代码更改为以下内容来解决问题:
public PageOf()
{
Items = new List<TModel>();
}
似乎 AutoMapper 2.0.0 正在丢弃 Items 属性中的任何值并使用 set
属性访问器,而 AutoMapper 2.2.0 仅使用 get
属性访问器并尝试修改现有的 IEnumerable。看起来像 Enumerable.Empty<TModel>()
只是替换一个零长度数组,这可以解释异常。
这是一个错误吗? AutoMapper 在 2.0.0 和 2.2.0 之间发生了什么变化,导致它忽略目标属性 setter ,而是尝试修改现有集合?
更新:
根据要求,这是 CreateMap 调用:
public class PagedQueryResultToPageOfItemsProfiler : Profile
{
protected override void Configure()
{
CreateMap<PagedQueryResult<EstablishmentView>, PageOfEstablishmentApiModel>();
}
}
PageOfEstablishmentApiModel
类继承自 PageOf<EstablishmentApiModel>
.
这是 Mapper.Map 代码:
var query = Mapper.Map<EstablishmentViewsByKeyword>(input);
var results = _queryProcessor.Execute(query);
var model = Mapper.Map<PageOfEstablishmentApiModel>(results); // exception here
如果需要特殊的映射配置(for example .ConvertUsing(x => x))在从 2.0.0 到 2.2.0 的 AutoMapper 中,我们可能不得不卡在旧版本上。我一直很喜欢 AM 自动转换集合属性的方式,如果没有它,AM 看起来更像是 ValueInjecter。
最佳答案
您是否尝试过以这种方式使用 Map 方法:
Mapper.Map<DestinationClass, SourceClass>(object to convert)
?
对于 2.2 版的 AutoMapper,我们就是这样使用它的,它对我们来说工作得很好。
关于c# - 这是 AutoMapper 2.0.0 和 2.2.0 之间的重大变化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13501702/