0

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

像这样的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
   {
      //...
   }
4

2 回答 2

0

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

于 2013-10-15T10:36:58.337 回答
0

SubCategoriesare virtual,这意味着延迟加载。这意味着,除非您请求,否则不会检索该表。使用Include方法。

public ActionResult Index()
{
    return View(database.Categories.Include("SubCategory").ToList());
}
于 2013-10-15T10:24:04.783 回答