我有一个对象
public class Tenant : EntityBase
{
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual string CreatorName { get; set; }
public virtual TenantState State { get; set; }
public virtual Address Address { get; set; }
public virtual IList<TenantActivity> Activities { get; set; }
public virtual IList<AppUser> Users { get; set; }
public virtual IList<TenantConfig> TenantConfigs { get; set; }
....
}
像这样的 DTO:
public class TenantDto
{
public Guid Id { get; set; }
public DateTime CDate { get; set; }
public string CUser { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string CreatorName { get; set; }
public TenantState State { get; set; }
public AddressDto Address { get; set; }
public List<TenantActivityDto> Activities { get; set; }
public List<AppUserDto> Users { get; set; }
public List<TenantConfigDto> TenantConfigs { get; set; }
....
}
类(class)Address
是一个 ValueObject,它也有一个 DTO。我使用以下映射(标准,无特殊配置)
public class TenantMapperProfile : Profile
{
protected override void Configure()
{
CreateMap<Tenant, TenantDto>();
CreateMap<TenantDto, Tenant>();
}
}
public class AddressMapperProfile : Profile
{
protected override void Configure()
{
CreateMap<Address, AddressDto>();
CreateMap<AddressDto, Address>();
}
}
在我的 App.xaml.cs 中我有:
var mapperConfig = new MapperConfiguration(cfg =>
{
cfg.AddProfile<TenantMapperProfile>();
cfg.AddProfile<TenantActivityMapperProfile>();
cfg.AddProfile<AppUserMapperProfile>();
cfg.AddProfile<AddressMapperProfile>();
//cfg.ShouldMapProperty = p => p.SetMethod.IsPrivate || p.GetMethod.IsAssembly;
});
Mapper = mapperConfig.CreateMapper();
然后我在这样的服务中调用它:
public TenantDto CreateTenant(TenantDto tenantDto)
{
tenantDto.CreatorName = creatingUserName;
var tenant = _mapper.Map<Tenant>(tenantDto);
tenant = _tenantManagerService.CreateTenant(tenant);//<-- Screenshot made here
return _mapper.Map<TenantDto>(tenant);
}
在第一次调用 mapper 后,我制作了调试器窗口的屏幕截图。如您所见tenantDto
实例包含 Address
中的数据对象但是 tenant
对象包含正确映射的自己的数据,但嵌套的 Address
对象只有空值!我在这里做错了什么??
编辑 - 附加信息
调用 mapperConfig.AssertConfigurationIsValid();
返回一个错误:
The following property on Bedisoco.BedInventory.Sys.Models.Entities.Role cannot be mapped: Roles Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type Bedisoco.BedInventory.Sys.Models.Entities.Role.
Role
对象在其中一个列表中的某处,我认为 User
List<AppUser>
中的对象集合本身包含 Role
的列表对象。它甚至没有完全实现。
我假设 Automapper 会默默地忽略这些事情是错误的吗?
最佳答案
好的,解决了,是我自己的问题。
我的大多数值对象都包含一个包含所有字段的构造函数和一个私有(private) setter 。如果配置正确 (cfg.ShouldMapProperty = p => p.SetMethod.IsPrivate || p.GetMethod.IsAssembly;
),私有(private) setter 对 Automapper 没有问题。
但 VS 或 ReSharper 建议将自动属性设置为“只获取”。这种重构取悦 VS 但不是 Automapper!
关于c# - 使用 Automapper 映射后嵌套对象成员为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38296184/