1. in Order model:
public class Order
{
public int Id { get; set; }
public DateTime OrderDate { get; set; }
public string OrderNumber { get; set; }
public ICollection<OrderItem> Items { get; set; }
}
if I want to use /api/orders/{orderid}/items to get items, I have to create association controller for
Items
2. create OrderItemsController in Controller folder
[Route("/api/orders/{orderid}/items")]
public class OrderItemsController : Controller
{
private readonly IDutchRepository repository;
private readonly ILogger<OrderItemsController> logger;
private readonly IMapper mapper;
public OrderItemsController(IDutchRepository repository,
ILogger<OrderItemsController> logger
, IMapper mapper)
{
this.repository = repository;
this.logger = logger;
this.mapper = mapper;
}
[HttpGet]
public IActionResult Get(int orderId)
{
var order = this.repository.GetOrderById(orderId);
if (order != null) return Ok(this.mapper.Map<IEnumerable<OrderItem>, IEnumerable<OrderItemViewModel>>(order.Items));
return NotFound(order.Items);
}
[HttpGet("{id}")]
public IActionResult Get(int orderId, int id) {
var order = this.repository.GetOrderById(orderId);
if (order != null)
{
var orderItem = order.Items
.Where(o => o.Id == id)
.FirstOrDefault();
if (orderItem != null) {
return Ok(this.mapper.Map<OrderItem, OrderItemViewModel>(orderItem));
}
}
return NotFound(order.Items);
}
}
3. in OrderItem model
public class OrderItemViewModel
{
public int Id { get; set; }
[Required]
public int Quantity { get; set; }
[Required]
public decimal UnitPrice { get; set; }
[Required]
public int ProductId { get; set; }
public string ProductCategory { get; set; }
public string ProductSize { get; set; }
public string ProductTitle { get; set; }
public string ProductArtist { get; set; }
}
if I add property with prefix of Product, AutoMapper will map product properties value automatically and show
when url is called