What is the best way to debug an ObjectContext object located in .NET MVC

I am trying to show an object property in my view if it exists, otherwise it returns to the default value, for example.

@if(Product.Description != null && Product.Description.Color != null){
    <li>@Product.Description.Color</li>
}

The problem is that if I do a null check in the view, the ObjectContext was deleted for Product.Description if it does not exist and an exception is thrown.

Should I assign a default value / return to my controller or is there a way to handle this in the view?

+4
source share
2 answers

"" . , . , .

, .

, , "M" M VC "Domain M odel", , , Entity Framework. , .

AutoMapper, EF , (ViewModel).

+7

, , , :

public ActionResult Index()
{
  var db = new MyDbContext();

  var model = db.Products.FirstOrDefault();

  return View(model);
}

:

public ActionResult Index()
{
  var model = new IndexVM();

  using (var db = new MyDbContext())
  {
    // Assuming EF
    var dbProduct = db.Products.FirstOrDefault();
    // Even better performance:
    var dbProduct = db.Products
      // prevent lazy loading
      .Include(p => p.Description.Color)
      .FirstOrDefault()
      // prevent ef tracking with proxy objects
      .AsNoTracking();

    // can be automated with AutoMapper or other .Net Components
    ProductVM productVM = new ProductVM();
    productVM.Id = dbProduct.Id;
    // etc

    // Don't put logic in View:
    productVM.HasDescription = (product.Description != null);
    if (productVM.HasDescription)
    {
       var descriptionVM = new DescriptionVM();
       // map values
       productVM.Description = descriptionVM;
    }

    model.Product = productVM;
  }

  return View(model);
}

per-se:

@if(product.HasDescription && product.Description.HasColor){
  <li>@Product.Description.Color</li>
}
+4

All Articles