【发布时间】:2019-10-26 17:16:48
【问题描述】:
如何在此处显示子数据 我有两个模型 Book(父)和 Author(子)。 我想在视图中显示作者姓名,但在 Book 模型中,我有带有空引用的 Author 对象,但 AuthorId 的值为 1。
当我使用 DbContext 对象获取 Book 数据时,我成功在控制器中获取子值我搜索作者数据,我不知道这是正确的方法,因为我是 ASP.NET MVC 的新手,或者存在更好的连接解决方案父子数据之间的数据?
这是我的控制器和模型类。
public ActionResult Book(int id)
{
var book = dbContext.Books.SingleOrDefault(b => b.ID == id);
if(book.AuthorId != null)
{
book.Author = dbContext.Authors.SingleOrDefault(a => a.ID == book.AuthorId);
}
return View(book);
}
图书模型类。
public class Book
{
[Key]
public int ID { get; set; }
public string Title { get; set; }
public decimal Score { get; set; }
public Format Format { get; set; }
public Language Language { get; set; }
[ForeignKey("Author")]
public int? AuthorId { get; set; }
public Author Author { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public decimal Discount { get; set; }
}
还有这个子模型作者
public class Author
{
[Key]
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Book> Books { get; set; }
}
编辑: 解决方案是使用可以在此命名空间 System.Data.Entity 中找到的 Include 扩展方法。
public ActionResult Book(int id)
{
var book = dbContext.Books
.Include(a => a.Author)
.Include(p => p.ProductDetails)
.SingleOrDefault(b => b.ID == id);
return View(book);
}
【问题讨论】:
-
我发现了 Include 扩展方法,它就像魅力 :),使用这个命名空间 System.Data.Entity;
标签: c# asp.net-mvc model-view-controller