我正在嘗試將我的 ProductDto 映射到 Product 類。將 ProductDto 類中的字串屬性映射到 Product 類中的 Brand 屬性時出錯
AutoMapper.AutoMapperMappingException: Error mapping types.
Mapping types:
ProductDto -> Product
SilksyAPI.Dto.ProductDto -> SilksyAPI.Entities.Product
Type Map configuration:
ProductDto -> Product
SilksyAPI.Dto.ProductDto -> SilksyAPI.Entities.Product
Destination Member:
Brand
---> AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.
Mapping types:
String -> Brand
System.String -> SilksyAPI.Entities.Brand
這是我的映射組態檔:
CreateMap<Product, ProductDto>()
.ForMember(dest => dest.Brand, opt => opt.MapFrom(p => p.Brand.Name))
.ForMember(dest => dest.Categories, opt => opt.MapFrom(p => p.ProductCategories.Select(pc => pc.Category.Name)));
CreateMap<ProductDto, Product>()
.ForMember(dest => dest.Brand, opt => opt.MapFrom(src => src.Name));
課程:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int BrandId { get; set; }
public Brand Brand { get; set; }
public ICollection<ProductCategory> ProductCategories { get; set; }
}
public class Brand
{
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
}
Dto 類
public class ProductDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Brand { get; set; }
public List<string> Categories { get; set; }
}
我嘗試了不同的映射組態檔,但我無法從 ProductDto 映射到產品,但可以毫無問題地從 Product 映射到 ProductDto。
這是我嘗試過的其他一些事情
CreateMap<Brand, string>()
.IncludeMembers(b => b.Name);
CreateMap<Product, ProductDto>()
.ForMember(dest => dest.Brand, opt => opt.MapFrom(p => p.Brand.Name))
.ForMember(dest => dest.Categories, opt => opt.MapFrom(p => p.ProductCategories.Select(pc => pc.Category.Name)))
.ReverseMap();
和
Mapper.CreateMap<Brand, string>().ConvertUsing(source => source.Name ?? string.Empty);
https://docs.automapper.org/en/stable/Flattening.html
有人可以幫忙嗎
uj5u.com熱心網友回復:
從你的第一個映射分布,當從映射ProductDto到Product,為Brand財產,你需要創建一個新的Brand實體如下:
cfg.CreateMap<ProductDto, Product>()
.ForMember(dest => dest.Brand, opt => opt.MapFrom(src => new Brand { Name = src.Name }));
示例程式
為了
.IncludeMembers()
我認為它不適合您的情況,因為您要從objectto映射string而不是objectto object。
為了
.ConvertUsing()
您需要將下面的代碼添加到從string到Brand為品牌屬性的映射。
cfg.CreateMap<string, Brand>()
.ConvertUsing(source => new Brand { Name = source });
示例程式 ( .ConvertUsing())
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354060.html
