问题描述
这是我的代码:
型号:
public class Category
{
[Key]
public string Cat_ID { get; set; }
public string Cat_Name { get; set; }
}
/////////////////////////////////////////////////////////
public class SubCategory
{
[Key]
public string SCat_ID { get; set; }
public string SCat_Name { get; set; }
[ForeignKey("SCat_Cat")]
public string SCat_Cat { get; set; }
public virtual Category Category { get; set; }
}
SubCategory控制器(视图部分):
public SubCategoriesController(ApplicationDbContext context)
{
_context = context;
}
// GET: SubCategories
public async Task<IActionResult> Index()
{
return View(await _context.SubCategory.ToListAsync());
}
@foreach (var item in Model) {
<tr>
<td>
@Html.displayFor(modelItem => item.SCat_Name)
@Html.displayFor(modelItem => item.Category.Cat_Name)
</td>
因此,我试图使此部分@Html.displayFor(modelItem => item.Category.Cat_Name)
显示类别名称。现在我什么也没得到。
哦,这是数据库记录。
解决方法
必须对此进行更改:
public async Task<IActionResult> Index()
{
return View(await _context.SubCategory.ToListAsync());
}
对此:
public async Task<IActionResult> Index()
{
return View(await _context.SubCategory.Include(u => u.Category).ToListAsync());
}