Automapper 双向复杂映射

Automapper bidirectional complex mappings

我在配置 Automapper 时遇到问题,无法达到预期的效果。

我有 3 个实体:

public abstract class Item
{

    public Guid Id { get; set; }
    public string Name { get; set; }

}
public class Ingredient
{

    public Guid Id { get; set; }
    public Item Item { get; set; }
    public int Quantity { get; set; }

}
public class ConstructionItem : Item
{

    public Guid Id { get; set; }
    public List<Ingredient> Recipe { get; set; };

}

对于每个实体,我都有一个对应的 dto :

public abstract class ItemDto
{

    public Guid Id { get; set; }
    public string Name { get; set; }

}
public class IngredientDto
{

    public Guid ItemId { get; set; }
    public int Quantity { get; set; }

}
public class ConstructionItemDto : ItemDto
{

    public List<IngredientDto> Recipe { get; set; }

}

我还有2个请求模型:

public class CreateConstructionItemRequest {

    public string Name { get; set; }
    public List<IngredientDto> Recipe { get; set; }

}
public class UpdateConstructionItemRequest {

    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<IngredientDto> Recipe { get; set; }

}

问题:

感谢您的帮助!

编辑 1:

这是我试过的方法:

public class GeneralProfile : Profile
{
    public GeneralProfile()
    {
        CreateMap<Ingredient, IngredientDto>()
            .ForMember(x => x.Item, opt => opt.MapFrom(x => x.Item.Id));

        CreateMap<CreateConstructionItemRequest, ConstructionItem>();

        CreateMap<UpdateConstructionItemRequest, ConstructionItem>();

        CreateMap<ConstructionItem, ConstructionItemDto>();
    }
}

问题:

编辑 2:

错误:

AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
CreateConstructionItemRequest -> ConstructionItem
MyApp.Application.Features.ConstructionItems.Commands.CreateConstructionItemRequest -> MyApp.Domain.Entities.ConstructionItem

Type Map configuration:
CreateConstructionItemRequest -> ConstructionItem
MyApp.Application.Features.ConstructionItems.Commands.CreateConstructionItemRequest -> MyApp.Domain.Entities.ConstructionItem

Destination Member:
Recipe

 ---> AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types:
IngredientDto -> Ingredient

您可以使用一个请求模型代替您的两个模型:

public class ConstructionItemRequest {
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<IngredientDto> Recipe { get; set; }
}

对于映射配置文件试试这个:

public GeneralProfile()
{
    CreateMap<Ingredient, IngredientDto>().ReverseMap();
    CreateMap<Item, ItemDto>().ReverseMap();            
    CreateMap<ConstructionItemRequest, ConstructionItem>().ReverseMap();
    CreateMap<ConstructionItem, ConstructionItemDto>().ReverseMap();
}