“一对多关系”字段始终为空

时间:2013-10-15 10:16:14

标签: entity-framework asp.net-mvc-4

大家好当我尝试使用Model.SubCategories但它始终为null。我什么都不懂。

MyModel是这样的:

public class Category
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int CategoryID { get; set; }

    public string Name { get; set; }
    public virtual IEnumerable<SubCategory> SubCategories { get; set; }
}

public class SubCategory
{
    [Key]
    public int SubCategoryID { get; set; }

    public string Name { get; set; }

    [ForeignKey("Category")]
    public int CategoryID { get; set; }
    public virtual Category Category { get; set; }

}

DBContext赞这个:

public class EntitiesContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<SubCategory> SubCategories { get; set; }
}

我的行动就像这样:

public ActionResult Index()
    {
        return View(database.Categories.ToList());
    }

我的观点片段像这样:

 @foreach (var item in Model.SubCategories) //always null
   {
      //...
   }

2 个答案:

答案 0 :(得分:0)

SubCategoriesvirtual,表示延迟加载。这意味着,除非您提出要求,否则不会检索该表。使用Include方法。

public ActionResult Index()
{
    return View(database.Categories.Include("SubCategory").ToList());
}

答案 1 :(得分:0)

尝试将SubCategory属性声明为ICollection而不是IEnumerable