【问题标题】:Unable to fetch data for a many to many table property无法获取多对多表属性的数据
【发布时间】:2021-10-01 07:12:29
【问题描述】:

您好,我需要帮助。

我正在使用 ASP.Net Core 3.0 和 EF Core... 我需要编辑一个具有导航属性的多对多表。

我尝试了下面的代码,我可以获取发票数据,但我在 ProductInvoices 属性上得到空值,该属性也是多对多关系表的链接。

        // GET: Invoices/Edit
        public async Task<IActionResult> Edit(int? id)
        {

            var invoice = await _context.Invoices.Where(i => i.InvoiceId == id).FirstOrDefaultAsync();

            return View(invoice);
        }
    public class Product
    {
        [Key]
        public int ProductId { get; set; }

        public int ProductsItemInStock { get; set; }

        public decimal CostPerItem { get; set; }

        public string ItemName { get; set; }

        public IList<ProductInvoice> ProductInvoices { get; set; }
    }


    public class Invoice
    {
        [Key]
        public int InvoiceId { get; set; }

        public DateTime CreatedDate { get; set; }

        public Guid CreateByUser { get; set; }

        public int TotalInvoice { get; set; }

        public IList<ProductInvoice> ProductInvoices { get; set; }
    }
    
        public class ProductInvoice
    {
        [Key]
        public int ProductId { get; set; }
        public Product Product { get; set; }

        [Key]
        public int InvoiceId { get; set; }
        public Invoice Invoice { get; set; }
    }

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-core entity-framework-core


【解决方案1】:

试试这个

    public async Task<IActionResult> Edit(int? id)
    {

        var invoice = await _context.Invoices.Include("ProductInvoices").Where(i => i.InvoiceId == id).FirstOrDefaultAsync();

        return View(invoice);
    }

【讨论】:

  • 你能告诉我一个可以学习 EF Core 的好教程吗?因为我确实阅读了 EF Core 的 MSDN 官方文档,但我找不到
  • MSDN 文档是完整的资源,但对于新手来说,您可以通过观看有关主题的 youtube 视频来学习,但最好的方法是边做边学。你可以关注entityframeworktutorial.net,但一定要练习。
  • 您也可以使用 lambda 版本,例如 _context.Invoices.Include(x=>x.ProductInvoices)
猜你喜欢
  • 1970-01-01
  • 2017-03-10
  • 2017-04-27
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 2015-05-27
  • 2012-03-26
  • 1970-01-01
相关资源
最近更新 更多