1
public class Entity
{
public int Id { get; set; }
}
public class User : Entity
{
public string Name { get; set; }
public Company Company { get; set; }
}
public class Company : Entity
{
public string Name { get; set; }
}
DTO的:
public class EntityDto
{
public int Id { get; set; }
}
public class UserDto : EntityDto
{
public string Name { get; set; }
public int? CompanyId { get; set; }
}
所以我要地图User
到UserDto
像User.Company == null
=>
UserDto.CompanyId == null
,反之亦然。
这是我Automapper配置:
Mapper.Initialize(configuration =>
{
configuration
.CreateMap<User, UserDto>()
.ReverseMap();
});
这工作得很好:
[Fact]
public void UnattachedUserMapTest()
{
// Arrange
var user = new User { Company = null };
// Act
var userDto = Mapper.Map<User, UserDto>(user);
// Assert
userDto.CompanyId.Should().BeNull();
}
但此测试失败:
[Fact]
public void UnattachedUserDtoMapTest()
{
// Arrange
var userDto = new UserDto { CompanyId = null };
// Act
var user = Mapper.Map<UserDto, User>(userDto);
// Assert
user.Company.Should().BeNull();
}
详情:
Expected object to be <null>, but found
Company
{
Id = 0
Name = <null>
}
不为我工作:
...
.ReverseMap()
.ForMember(user => user.Company, opt => opt.Condition(dto => dto.CompanyId != null));
和以及作为(只是举例):
...
.ReverseMap()
.ForMember(user => user.Company, opt => opt.Ignore());
为什么Automapper创建嵌套的对象,我该如何预防呢?
所以我想我不能够使用条件映射会员?忽略对我来说仍然可以,但我只想知道) –
您的意思是[this](https://github.com/AutoMapper/AutoMapper/issues/2298)? –
是的,确切地说。很高兴看到它即将推出。 –