L
L
lucky42021-06-21 23:06:37
ASP.NET
lucky4, 2021-06-21 23:06:37

How to add a new entry with nesting?

I need to make a relatively simple functionality for adding a product to a product list.

There are DTO entities:

public class WishlistItemDto
    {
        public int Id { get; set; }

        public string CustomerId { get; set; }

        public ProductDetailsDtoWithPrimaryImage ProductDetails { get; set; }

        public int Quantity { get; set; }
    }

public class WishListItemCreationDto
    {
        public string CustomerId { get; set; }

        public int ProductDetailId { get; set; }

        public int Quantity { get; set; }
    }


There was a problem adding an item to the list. Here's what the code looks like:
//Controller
        [HttpPost]
        public async Task<IActionResult> Add(WishListItemCreationDto wishListItemDto)
        {
            var itemAdd = _mapper.Map<WishlistItemDto>(wishListItemDto);
            var itemCreated = await _wishListItemService.AddAsync(itemAdd);

            return CreatedAtAction(nameof(GetId), new { id = itemCreated.Id }, wishListItemDto);
        }

        //Service
        public async Task<WishlistItemDto> AddAsync(WishlistItemDto item)
        {
            var entity = _mapper.Map<WishlistItem>(item);
            var entityDetails = await _productDetailsRepository.GetById(item.ProductDetails.Id);
            entity.ProductDetails = entityDetails;
            await _wishListItemRepository.AddAsync(entity);

            return _mapper.Map<WishlistItemDto>(entity);
        }


The entityDetails variable (in the service) is always null. And I can't figure out how to transfer the data (request to add a product)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2021-06-22
@yarosroman

Obviously the mapper doesn't reflect the nested object to you.

itemAdd.ProductDetails = wishListItemDto.ProductDetails;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question