AutoMapper:地图DTO回与子对象的域对象对象、与子、地图、AutoMapper

2023-09-03 04:05:44 作者:晚吟

比方说,我有两个对象,我想图:

Let's say I have two objects I'd like to map:

// Domain objects
public class MyDomainObject
{
    public string SimpleText { get; set; }
    public int SimpleNumber { get; set; }
    public MySubObject ComplexValue { get; set; }
}

public class MySubObject
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// DTOs
public class MyDto
{
    public string SimpleText { get; set; }
    public int SimpleNumber { get; set; }
    public int ComplexValueId { get; set; }
    public string ComplexValueName { get; set; }
}

// Mapping config
Mapper.CreateMap<MyDomainObject, MyDto>();

THS将正常工作,无需额外的配置,因为AutoMapper将着眼于驼峰规则,然后向下钻取。

现在我想为映射DTO回域对象: Mapper.Map&LT; MyDto,MyDomainObject&GT;(DTO,domainObj);

Now I'd like to map the DTO back to the domain object: Mapper.Map<MyDto, MyDomainObject>(dto, domainObj);

会是什么样的最佳/最简单的映射配置是实现呢?

What would the best/simplest mapping configuration be to achieve it?

推荐答案

发现在另一篇文章的解决方案: 使用AutoMapper到unflatten一个DTO

Found the solution in another post: Using AutoMapper to unflatten a DTO

我喜欢最后的答案,除非更好的方法可以建议。

I like the last answer, unless better ways can be suggested.