Error getting foreign key data on entity
I'm new in MVC2 and Entity Framework and I tried get a list of products with the respective category name, but it's returned me the error
"Object reference not set to an instance of an object."
I have a tab开发者_如何学Cle Product
with a foreign key Category
.
I'm using MVC2 and Entity Framework 4.0.
public class Repository
{
public IQueryable<Produto> ListAllProducts()
{
return entities.Produtos;
}
}
public class AdminProdutoController : Controller
{
TudoDeMassinhaRepository repository = new TudoDeMassinhaRepository();
public ActionResult Index()
{
var produtos = repository.ListAllProducts().ToList();
return View(produtos);
}
}
code in view where the error is generated: <%: item.CatProduto.cat_produto_nome%>
You're only selecting the products - you're not currently including the categories. This means: you'll get back your product objects, but any related objects they refer to are not loaded automatically - that's why the .CatProduto
property will be NULL and thus you're getting the error.
You need to explicitly specify which additional entities you want to have loaded - something like:
public IQueryable<Produto> ListAllProductsWithCategories()
{
return entities.Produtos.Include("CatProduto");
}
This way, you should get back your Produto
objects, and their CatProduto
property should have been loaded and populated, too.
So if you change your index method to be:
public ActionResult Index()
{
var produtos = repository.ListAllProductsWithCategories().ToList();
return View(produtos);
}
it should work.
精彩评论