Home > Net >  How to shape return data?
How to shape return data?

Time:12-29

While returning data in Postman, I receive full user information such as password hash and password salt. My idea is to return only his username, so that it looks like "user" : "tom" without his data. I should use automapper ? Or how to set the Dto's to return correct data. Any tips ?

public async Task < ActionResult < ProductDto[] >> AddProduct(string username,
ProductDto productDto) 
{
    User u = await _context.Users
                           .Where(x => x.UserName == username)
                           .Include(x => x.Products)
                           .SingleOrDefaultAsync();

    if (u != null) 
    {
        var product = new Product 
                          {
                              Name = productDto.Name,
                              Price = productDto.Price,
                              UserId = u.Id
                          };
        u.Products.Add(product);
        await _context.SaveChangesAsync();
    }

    return u.Products.ToArray();
}

public class Product : BaseEntity
{
    public string Name { get; set; }
    public decimal Price { get; set ;}
    public User User { get; set; }
    public int UserId { get; set; }
}

public class ProductDto
{
    public string Name { get; set; }
    public string Username { get; set; }
    public decimal Price { get; set; }
}

Output in postman: https://i.stack.imgur.com/vNi7J.png

CodePudding user response:

You are returning an array of Product objects, but it seems that what you really want is to return an array of ProductDto objects.

You can use the following code to construct the array of ProductDto objects. Insert it after the if (u != null) check:

var productDtos = new ProductDto[u.Products.Count] { };
for (var i = 0; i < u.Products.Count; i  )
{
    productDtos[i] = new ProductDto
    {
        Name = product.Name,
        Username = product.User.UserName,
        Price = product.Price
    };
}

return productDtos;

Alternatively, you can use LINQ:

var productDtos = u.Products
    .Select(p => new ProductDto
    {
        Name = p.Name,
        Username = p.User.UserName,
        Price = p.Price
    })
    .ToArray();

return productDtos;
  • Related