在我的情况下,我有 3 个实体。发票、发票明细和项目。Invoice 有一个 InvoiceDetail 的集合。每个 InvoiceDetail 都有一个 Item。
请看下面的代码:
var ctx = new TestEntities();
var newInvoice = new Invoice
{
CreationDate = DateTime.Now,
UserId = 14
};
newInvoice.InvoiceDetails.Add(new InvoiceDetail
{
ItemId = 345,
ItemCount = 10
});
newInvoice.InvoiceDetails.Add(new InvoiceDetail
{
ItemId = 534,
ItemCount = 10
});
ctx.Invoices.Add(newInvoice);
ctx.SaveChanges();
// workaround
// ctx.Items.ToList();
foreach (var i in newInvoice.InvoiceDetails)
{
// In this line I get NullReferenceException
Console.WriteLine(i.Item.Title);
}
当我想检索每个 InvoiceDetail 的 Item 数据时,我得到 NullReferenceException。
当我取消注释,注释部分代码时,问题就解决了。(ctx.Items.ToList())
更新 1:
这也是 Item 类:
public partial class Item
{
public Item()
{
this.InvoiceDetails = new HashSet<InvoiceDetail>();
}
public long Id { get; set; }
public string Title { get; set; }
public virtual ICollection<InvoiceDetail> InvoiceDetails { get; set; }
}
更新 2:
public partial class InvoiceDetail
{
public long Id { get; set; }
public long InvoiceId { get; set; }
public long ItemId { get; set; }
public int ItemCount { get; set; }
public virtual Invoice Invoice { get; set; }
public virtual Item Item { get; set; }
}