首页 > 解决方案 > 无法将类型 dto 转换为类型 Ienumerable

问题描述

我正在创建一个 asp.net 核心 web.api 并且需要从 Ienumerable 方法返回 DTO 对象。我在控制器获取方法中遇到错误,说无法将 DTO 转换为 Ienumerable 类型

 namespace Products.DTO
{
    public class Products
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
        public DateTime Available { get; set; }
        public decimal Price { get; set; }
    }

}

namespace Products.API.Controllers
{
     [Route("api/[controller]")]
        [ApiController]
        public class ProductsController : ControllerBase
        {

            [HttpGet]
            public ActionResult<IEnumerable<DTO.Products>> GetProducts()
            {
                return new DTO.Products  
                {
                    Id = 1, Name = "Cricket bat", Available = DateTime.Now, Code = "AC122333", Price = 1223.23M
                };
            }
        }
}

标签: asp.net-core-webapi

解决方案


试试这个方法

return new DTO.Products[]{  
    DTO.Products { Id = 1, Name = "Cricket bat", Available = DateTime.Now, Code = "AC122333", Price = 1223.23M }
};

推荐阅读