I have 2 entities:
public class ParentItem : BaseModel
{
public string Name { get; set; }
public IEnumerable<ChildItem> Items { get; set; }
}
public class ChildItem :BaseModel
{
public string Name { get; set; }
}
the BaseModel:
public class BaseModel
{
public Guid Id { get; set; }
public DateTime CreationDate { get; set; }
public DateTime UpdateDate { get; set; }
}
and 2 DTO:
public class ParentItemDto
{
public string Name { get; set; }
public IEnumerable<ChildItemDto> Items { get; set; }
}
public class ChildItemDto
{
public string Name { get; set; }
}
I have simple mappers defined for each entity:
CreateMap<ParentItem, ParentItemDto>().ReverseMap();
CreateMap<ChildItem, ChildItemDto>().ReverseMap();
After initializing a Parent and a ParentDto:
var parent = new ParentItem()
{
Id = Guid.NewGuid(),
CreationDate = DateTime.Now.AddDays(-2),
UpdateDate = DateTime.Now.AddDays(-1),
Name = "Parent",
Items = new List<ChildItem>()
{
new ChildItem()
{
Id = Guid.NewGuid(),
CreationDate = DateTime.Now.AddDays(-5),
UpdateDate = DateTime.Now.AddDays(-5),
Name = "Child 1"
},
new ChildItem()
{
Id = Guid.NewGuid(),
CreationDate = DateTime.Now.AddDays(-4),
UpdateDate = DateTime.Now.AddDays(-4),
Name = "Child 2"
}
}
};
var parentDto = new ParentItemDto()
{
Name = "Parent Dto",
Items = new List<ChildItemDto>()
{
new ChildItemDto()
{
Name = "Child 1 dto"
},
new ChildItemDto()
{
Name = "Child 2 dto"
}
}
};
I want to map the parentDto to parent
mapper.Map(parentDto, parent);
The problem is that the 'CreationDate', 'UpdateDate' and 'Id' fields of the 'ChildItem' are set to default value. But only for child object, values for parent object are kept.
Parent:
Child:
What should I change in order to have the child properties unmodified?
Thank you!
question from:
https://stackoverflow.com/questions/65834454/automapper-child-properties-set-to-default-value-after-mapping 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…