在Entity Framework中加载相关对象 - 空引用异常

时间:2017-04-26 12:36:18

标签: c# asp.net-mvc entity-framework-6

我正在尝试从我的数据库加载object Supplier。供应商有一个外键Adress,所以我使用Include方法加载供应商,但我得到了一个N​​ULL REFERENCE EXCEPTION。 这是我在Controller中的代码:

public ActionResult LoadSupplier(Supplier supplier)
        {
             if (supplier.SupplierID==0)
             {
                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
             }
          Supplier sup= db.Supplier
                 .Include(d => d.Adress)
                 .FirstOrDefault(x=>x.SupplierID==supplier.SupplierID);

             if (sup== null)
             {
                 return HttpNotFound();
             }
     return View(sup);
        }

我也尝试显式加载,但也得到空引用:

  var sup=  db.Supplier.Single(x=>x.SupplierID==supplier.SupplierID);
                      db.Entry(sup).Reference(d => d.Adress).Load();

我感谢任何建议或帮助!

0 个答案:

没有答案