对象引用未设置为Razor View中对象的实例

时间:2016-01-22 17:46:46

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

我有2个实体,即产品类别

public class ProductsController : Controller
    {
        private DemoContext db = new DemoContext();

        // GET: Products
        public ActionResult Index()
        {
            var products = db.Products.Include(p => p.Category);
            return View(products.ToList());
        }

        // GET: Products/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Product product = db.Products.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }
    }

产品控制器

<h2>@Model.Name</h2>
<label>@Model.Category.CategoryName</label>
<li>@Model.Price.ToString("##,###")</li>

我尝试在“产品详细信息”视图中以类别实体的形式访问CategoryName属性

aeVehicle.MSRP = float.Parse("0" + drInvetory["MSRP"].ToString());

但我收到错误“对象引用未设置为对象的实例。”

@ Model.Category.CategoryName

1 个答案:

答案 0 :(得分:1)

如果要将Category导航属性作为用于加载Product的查询的一部分加载,则应将查询更改为:

Product product = db.Products.Include(p=>p.Category).FirstOrDefault(p=>p.ProductId ==id);

这称为预先加载,您可以在此link

中详细了解它