错误NullReferenceException:对象引用未设置为对象的实例。 API加载相关数据时

时间:2019-12-30 16:35:11

标签: c# api asp.net-core

我在SQL Server中有一个本地存储的数据库,其中包含许多不同的表,它们通过不同类型的关系(一对多和多对多)连接在一起,

我的模型示例:

namespace OneClickAPI.Models
{
    public partial class ProductsTbl
    {
        public ProductsTbl()
        {
            BuyBillDetalisTbl = new HashSet<BuyBillDetalisTbl>();
            ItemMovmentTbl = new HashSet<ItemMovmentTbl>();
            ItemStoresTbl = new HashSet<ItemStoresTbl>();
            SaleBillDetialsTbl = new HashSet<SaleBillDetialsTbl>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public int? Qty { get; set; }
        public decimal? BuyPrice { get; set; }
        public decimal? SalePice { get; set; }
        public decimal? SaleGomla { get; set; }
        public decimal? AvgCost { get; set; }
        public int? QtyLimite { get; set; }
        public decimal? SaleLimite { get; set; }
        public int? CatId { get; set; }
        public int? BranchId { get; set; }

        public BranchTbl Branch { get; set; }
        public CatTbl Cat { get; set; }
        public ICollection<BuyBillDetalisTbl> BuyBillDetalisTbl { get; set; }
        public ICollection<ItemMovmentTbl> ItemMovmentTbl { get; set; }
        public ICollection<ItemStoresTbl> ItemStoresTbl { get; set; }
        public ICollection<SaleBillDetialsTbl> SaleBillDetialsTbl { get; set; }
    }
}

我试图使API从连接的表中获取数据 例如,我在Product controller.cs中编写了此代码:

 public class ProductsController : ControllerBase
    {
        private readonly OneClickDBContext _context;

        public ProductsController(OneClickDBContext context)
        {
            _context = context;
        }

        // GET: api/Products
        [HttpGet]
        public IEnumerable<ProductsTbl> GetProductsTbl()


        {
            var products =  _context.ProductsTbl
              .Include(p => p.BranchId)
              .Include(p => p.Cat)
              .Include(p => p.BuyBillDetalisTbl)
              .ToList();
            return _context.ProductsTbl;

        }

但是问题出在这个错误上 enter image description here

任何人都有解决此问题的想法 非常感谢

0 个答案:

没有答案