我在配置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; }
}
我还有两个请求模型:
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; }
}
问题:
- 如何将
CreateConstructionItemRequest
和UpdateConstructionItemRequest
绑定到实际的ConstructionItem
- 如何将
ConstructionItemDto
映射到ConstructionItem
,反之亦然
感谢您的帮助!
编辑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>();
}
}
问题:
- 无法将ConstructionItem映射到ConstructionItemDto
- 无法将CreateConstructionItemRequest映射到ConstructionItem
- 无法将UpdateConstructionItemRequest映射到ConstructionItem
编辑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();
}