大家好,当我尝试使用 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
{
//...
}