0

I have a receipt and category class. The receipt is the parent and category is the child. I am facing problem during mapping my parent to the child class, I get a null value from the child class dto even though I have set a value in the viewmodel.

Below are the codes that what I have tried.

This is DTO:

public class ReceiptDto
{
    public int ReceiptId { get; set; }
    public int CategoryId { get; set; }
}

public class CategoryDto
{
    public int CategoryId { get; set; }
}

This is my ViewModel:

public class ReceiptViewModel
{
    public int ReceiptId { get; set; }
    public CategoryViewModel CategoryVM { get; set; }
}

public class CategoryViewModel
{
    public int CategoryId { get; set; }
}

This is how I map using AutoMapper:

CreateMap<ReceiptDto, CategoryViewModel>(MemberList.None)
    .ReverseMap()
    .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

CreateMap<ReceiptDto, ReceiptViewModel>(MemberList.None)
    .ForMember(dest => dest.CategoryVM, opt => opt.MapFrom(src => Mapper.Map<ReceiptDto, CategoryViewModel>(src)))
    .ReverseMap()
    .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

CreateMap<CategoryDto, CategoryViewModel>(MemberList.None)
    .ReverseMap()
    .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

This is how I used it in Controller:

public async Task<IHttpActionResult> CreateReceipt(ReceiptViewModel receiptVM)
    {
        ReceiptDto receiptDto = Mapper.Map<ReceiptDto>(receiptVM);
    }

But then the CategoryId was null in my database. So I was thinking the problem is from the mapping, but I am not sure which part causes the problem. Thank you.

vomoxon
  • 63
  • 5

0 Answers0