I am building an ASP.NET MVC 5 "To Do List" app, where users can add categories and add tasks to categories. I am using Entity Framework 7 with a sort of "Code First" approach, but using an existing database.
I created a database in Microsoft SQL Server Management Studio with a Category
and an Item
table, and each Item
has a CategoryId
column that is a foreign key to the Category's Id
column.
Then I created an empty MVC5 app, with a database connection to this database. I created an Item
class and a Category
class in the Models folder that correspond to the tables in the database.
Item class:
namespace ToDoList.Models
{
[Table("Item")]
public partial class Item
{
public int ItemId { get; set; }
public string Description { get; set; }
[ForeignKey("Category")]
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
}
Category class:
namespace ToDoList.Models
{
[Table("Category")]
public partial class Category
{
public Category()
{
this.Items = new HashSet<Item>();
}
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
}
I want the view for an Item
to display its Category
's Name
property. The model for the view is a collection of all Item
s in the Item
table (IEnumerable<ToDoList.Models.Item>
). Say I want to print a list with each item followed by the name of the category related to it. Here's the code that I have:
<ul>
@foreach(var item in Model)
{
<li>@Html.DisplayFor(modelItem => item.Description) @Html.DisplayFor(modelItem => item.Category.Name)</li>;
}
</ul>
The Item
shows up just fine, but the page doesn't display anything for the Category
. This same code actually worked when I used an ADO.NET Entity Data Model to create classes, but I'm not able to create an Entity Data Model using ASP.NET 5, so I'm trying out this code-first approach.
Any ideas on why the app isn't using the foreign key relationship or suggestions of what I can try?
You can use eager loading to include the Category
in the query, using:
var model = db.Items.Include("Category").ToList();
or
var model = db.Items.Include(x=>x.Category).ToList();
and then return the view: return View(data);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments