【问题标题】:Show child data in View MVC在 View MVC 中显示子数据
【发布时间】: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


【解决方案1】:

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

Adding Foreign Key

【讨论】:

  • 我的工作与此链接下页面上显示的工作相同。但是当我通过 BookController 中的 DbContext 对象获取数据时,我拥有除 Author 对象之外的所有数据,我也有 AuthorId 数据,在我的案例 1 中。我想知道在获取 Book 数据时有什么方法可以获取 Author 数据。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 2021-08-28
  • 2021-11-12
  • 2017-08-15
  • 1970-01-01
  • 2011-04-12
  • 2012-11-23
相关资源
最近更新 更多