MVC3 EF Code First“外键”数据

时间:2012-04-18 12:44:39

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

我来自webforms,我正在尝试在MVC中复制一个简单的数据模型。我是.NET和C#新手,请原谅我这是一个非常简单的问题。我有“信件”,每个都有一个类别和多个收件人。 EF似乎在SQL后端正确创建了我的数据模型,但我无法访问视图中的类别。这是我的模特:

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; }
    }
}

详细信息页面的控制器代码:

//
// GET: /Letter/Details/5

public ViewResult Details(int id)
{
    Letter letter = db.Letters.Find(id);
    return View(letter);
}

查看代码尝试访问评论属性:

<div class="display-label">Category</div>
<div class="display-field">
     @Html.DisplayFor(model => model.Category.name)
</div>

1 个答案:

答案 0 :(得分:3)

您需要像收件人一样将其设为虚拟。

public virtual Category Category { get; set; }

将属性标记为“虚拟”会在创建代理时通知EF覆盖该属性。