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)? –
是的,確切地說。很高興看到它即將推出。 –