在视图MVC中显示子数据



如何在视图中显示子数据我有两个模型Book(父(和Author(子(。我想在视图中显示作者名称,但在Book模型中,我有一个引用为null的author对象,但AuthorId的值为1。

当我用DbContext对象获取Book数据时,我成功地在控制器中获取了子值。我搜索Author数据,我不知道这种方式是否正确,因为我是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; }
}

编辑:解决方案是使用Include扩展方法,该方法可以在此命名空间System.Data.Entity.中找到

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);
}

代码似乎没有任何错误。确保数据库表列名与属性名称完全匹配。并尝试在EF中添加forign密钥的不同方法。

添加外键

最新更新