Please help. I can not resolve the issue - the category name is null. Thanks a lot. The models public class Product { [Key] public int ProductID { get; set; } public string ProductName { get; set; } public string Description { get; set; } public double Price { get; set; }
public int CategoryID { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
}
` Product Controller
public async Task<IEnumerable<ProductDto>> GetProductsAsync()
{
List<Product> products = await _db.Products
.Include(u => u.Category)
.ToListAsync();
return _mapper.Map<List<ProductDto>>(products);
}
public class MappingProfiles : Profile
{
public MappingProfiles()
{
CreateMap<ProductDto, Product>().ReverseMap();
}
}
public class ProductDto
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string Description { get; set; }
public double Price { get; set; }
public string CategoryName { get; set; }
}
How to resolve null fields?
CodePudding user response:
Change your MappingProfiles
like below:
public class MappingProfiles : Profile
{
public MappingProfiles()
{
CreateMap<Product, ProductDto>()
.ForMember(d => d.CategoryName, a => a.MapFrom(s => s.Category.CategoryName))
.ReverseMap()
.ForPath(b => b.Category, o => o.MapFrom(dto => (Category)null));
}
}