我想创建一个从我们的实体模型到Dto的映射,但是我每次尝试创建映射都失败了。如何将具有嵌套属性的模型映射到平面Dto?
我有两个域类。这是我们的模型的简化(Device
例如有很多的属性,代表了一堆不同的东西):
class Device
{
public int Name {get; set;}
}
class DeviceAccessToken
{
public Device Device {get; set;}
public string Key {get; set;}
public string Secret {get; set;}
}
那么我想DeviceAccessToken
实例映射到此DeviceDto
(也简化了,它有最存在于原始Device
模型的字段):
class DeviceDto
{
public int Name {get; set;}
public string Key {get; set;}
public string Secret {get; set;}
}
有没有一种方法来创建没有明确指定映射中的Device
域模型的各个领域这种映射?
这实际上是我想要的,由AutoMapper轮廓表示:
class DeviceMappingProfile : Profile
{
protected override void Configure()
{
this.CreateMap<DeviceAccessToken, DeviceDto>();
this.CreateMap<Device, DeviceDto>()
.ForMember(dest => dest.Key, opt => opt.Ignore())
.ForMember(dest => dest.Secret, opt => opt.Ignore());
}
}
的.ForAllMembers
电话是一个失败的尝试,使这项工作,它必须不起作用像我想象它。
我知道我可以通过在DeviceAccessToken->DeviceDto
映射中指定Device
的每个属性来做到这一点,但这将是一场噩梦,并且非常冗余,因为名称相同。
小后我张贴我发现的问题[本文](https://github.com/AutoMapper/AutoMapper/wiki/Flattening )解释了你所谈论的这个约定,现在我决定使用它。但是有没有办法通过约定让automapper识别属性,而不必在嵌套属性名称前加前缀?就我而言,我必须创建两个非常相似的Dtos,因为其中一个需要有这个约定,而另一个则不需要。在某些地方,我需要将一个'Device'直接映射到'DeviceDto',这会使我的很多事情变得更简单。 – julealgon 2014-10-10 20:15:24
@julealgon嗨,我知道你的意思,但它似乎不同于原来的问题。我会创建一个新问题,你会得到更多的人试图回答它。我之前使用过INamingConvention更改惯例,这可能是您可以使用的。 https://github.com/AutoMapper/AutoMapper/blob/d6eaf7025932ebedccbf8c339a155e9f4ae5c5d8/src/AutoMapper/INamingConvention.cs – hutchonoid 2014-10-14 11:19:43