【问题标题】:What should I put to return one to many list in WebAPI?在 WebAPI 中返回一对多列表应该放什么?
【发布时间】:2019-07-03 18:18:27
【问题描述】:

我试图返回一个对象类,但是尝试失败了。

public class tbl_Product
{     
    public tbl_Product()
    {
        tbl_ProductDescription = new HashSet<tbl_ProductDescription>();
        tbl_ProductPricing = new HashSet<tbl_ProductPricing>();
    }

    public Guid Id { get; set; }      
    public string ProductCode { get; set; }
    public string ProductName { get; set; }
    public Decimal Price { get; set; }

    [InverseProperty("Product")]
    public virtual ICollection<tbl_ProductPricing> tbl_ProductPricing { get; set; }
 }

以下是我返回时的 WebAPI 函数:

[HttpGet]
public Task<ActionResult<ICollection<tbl_Product>>> GetProductList()
{
    var result = _context.tbl_Product
        .Include(a => a.tbl_ProductPricing).ToList();

    return result;
}

但是,我收到了这个错误:

Cannot implicitly convert type 'System.Collections.Generic.List<Model.tbl_Product>' to 'System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.ICollection<Model.tbl_Product>>>'

我可以知道我应该输入什么返回类型吗?

【问题讨论】:

    标签: c# entity-framework linq asp.net-core


    【解决方案1】:
    [HttpGet]
    public async Task<ActionResult<ICollection<tbl_Product>>> GetProductList()
    {
        return Ok(await _context.tbl_Product.Include(a => a.tbl_ProductPricing).ToListAsync());
    }
    

    返回的实例必须与方法签名中指定的类型匹配。在您的情况下,您指定返回类型为Task&lt;ActionResult&lt;ICollection&lt;tbl_Product&gt;&gt;&gt;,因此它必须1)返回一个Task,2)任务必须解析ActionResult&lt;ICollection&lt;tbl_Product&gt;&gt;的实例,3)ActionResult必须具有实现ICollection&lt;tbl_Product&gt;的内容.


    我假设您使用的是 .net 核心并引用 ActionResult&lt;T&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多