Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

c# - Automapper: child properties set to default value after mapping

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: enter image description here

Child: enter image description here

What should I change in order to have the child properties unmodified? Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...