TblBook.cs
public class TBLBook : IEntity
{
[Key]
public int BookId { get; set; }
public string BookName { get; set; }
[ForeignKey("TblCategory")]
public int CategoryId { get; set; }
public int WriterId { get; set; }
public string BookYearofPublication { get; set; }//Basım Yılı
public string BookPublishingHouse { get; set; } //Yayın evi
public string BookPage { get; set; }
public bool BookStatus { get; set; }
public TBLCategory TblCategory { get; set; }
}TblCategory.cs
public class TBLCategory : IEntity
{
[Key]
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<TBLBook> TblBooks { get; set; }
}我这样做是因为它是企业架构。
public class EfEntityRepositoryBase<TEntity, TContext> : IEntityRepository<TEntity>
where TEntity : class, IEntity, new()
where TContext : DbContext, new()
{
////return _context.Categories.Include(i => i.SubCategories).ToList();
public List<TEntity> GetList(Expression<Func<TEntity, bool>> filter=null)
{
using (TContext context = new TContext())
{
return filter == null ? context.Set<TEntity>().ToList() : context.Set<TEntity>().Where(filter).ToList();
}
}
}业务:
public List<TBLBook> GetList()
{
return _bookDal.GetList();
}控制器视图
public IActionResult Index()
{
var query = new BookListViewModel
{
TblBooks = _bookService.GetList()
};
return View(query);
}索引视图:
<tr>
<td>@b.BookId</td>
<td>@b.BookName</td>
<td>@b.WriterId</td>
<td>@b.CategoryId</td> <!--Problem: @b.TblCategory.CategoryName-->
<td>@b.BookYearofPublication</td>
<td>@b.BookPublishingHouse</td>
<td>@b.BookPage</td>
<td>@b.BookStatus</td>
</tr>我的问题是;当我这样做的时候,@b.TblCategories.CategoryName
抛出null或error。
我无法显示对应的类别名称。我怎样才能填满它,谢谢。我的英语不好,对不起。我试着用图片来解释。
简而言之,我想要做的是:显示类别ID。我希望它显示为类别名称。但是它看起来是空白的,我应该填什么呢?
屏幕截图:

发布于 2021-01-26 22:14:29
默认情况下,不加载相关实体。
此外,不要在数据库或代码中使用"TBL“前缀,也不要将DbContext包装在额外的存储库层中。它已经是一个存储库了。
因此,使用如下查询进行加载:
var books = db.Books.Include(b => b.Category).ToList();https://stackoverflow.com/questions/65902888
复制相似问题