I’m coming from webforms, and I’m trying to replicate a simple data model in MVC. I’m a .NET and C# novice, so excuse me if this is a really simple question. I have “Letters” that each have one category and multiple recipients. EF seems to create my data model correctly on the SQL backend, but I cant access the category in the view. Here is my model:
namespace FFLettersMVC.Models
{
public class Letter
{
public int id {get; set;}
public DateTime dateCreated { get; set; }
public string letterTitle { get; set; }
public DateTime dateMailed { get; set; }
public string createdBy { get; set; }
public string Type { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
public virtual ICollection<Recipient> Recipient { get; set; }
}
public class Category
{
public int id { get; set; }
public string name { get; set; }
}
public class Recipient
{
public int id { get; set; }
public int letterID { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public string ssnTin { get; set; }
public string email { get; set; }
public Letter Letter { get; set; }
}
}
Controller Code for Details Page:
//
// GET: /Letter/Details/5
public ViewResult Details(int id)
{
Letter letter = db.Letters.Find(id);
return View(letter);
}
View Code Attempting to access comments property:
<div class="display-label">Category</div>
<div class="display-field">
@Html.DisplayFor(model => model.Category.name)
</div>
You need to make it virtual, as you did the Recipient.
Marking the property as ‘virtual’ notifies EF to override the property when creating its proxies.