text 为api创建关联控制器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 为api创建关联控制器相关的知识,希望对你有一定的参考价值。

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

以上是关于text 为api创建关联控制器的主要内容,如果未能解决你的问题,请参考以下文章

使用 Windows API 获取文件关联

text 使用PowerShell创建AWS Systems Manager关联

Django Rest API,如何为 2 个模型条目创建 post api,并具有与模型关联的外键

怎样在文件夹选项中创建关联

如果通过 API 创建,Backand 用户对象不与自定义用户对象关联

text 测试api控制器