【发布时间】:2019-01-04 14:00:12
【问题描述】:
在一个项目中使用 Automapper,只是将 2 个对象相互映射,没什么特别的。我必须有一些配置不正确,因为 AutoMapper 一直说有未映射的属性。
这是 AutoMapper 配置。
var mapperConfig = new MapperConfiguration(cfg => {cfg.CreateMap<SrcObj, DestObj>()
.ForMember(dest => dest.Level, opt => opt.MapFrom(src => src.lvl));}
mapperConfig.AssertConfigurationIsValid();
SrcObj
public class SrcObj
{
public int Id { get; set; }
public int ParentNode { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public bool? IsActive { get; set; }
public string AreaName { get; set; }
public int? DisplayOrder { get; set; }
public Int64 Type{ get; set; }
public int lvl { get; set; }
}
目标对象
public class DestObj
{
public int Id { get; set; }
public int ParentNode { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public bool? IsActive { get; set; }
public string AreaName { get; set; }
public int? DisplayOrder { get; set; }
public Int64 Type{ get; set; }
public int Level { get; set; }
}
以及实施:
var items = await _context.Database.SqlQuery<SrcObj>($"EXEC spGenerateMenu {app1}").ToListAsync();
var rslt = _mapper.Map<DestObj>(items);
和错误:
{"\n找到未映射的成员。查看下面的类型和成员。\n添加自定义映射表达式...}
该错误实际上列出了 DestObj 的每个成员。不知道我错过了什么。可能很简单
【问题讨论】:
-
测试你的配置是否是valid,看看会发生什么。
-
我正在使用验证,它通过了...我将它添加到上面的示例中。
-
这一行
mapperConfig.AssertConfigurationIsValid();断言每个属性都已映射。 10 次中有 9 次会妨碍您。只需将其删除,或显式映射每个属性。
标签: c# .net entity-framework model-view-controller automapper