gpt4 book ai didi

c# - 在最近添加的记录中检索导航属性的数据

转载 作者:行者123 更新时间:2023-11-30 22:16:22 24 4
gpt4 key购买 nike

我的案例中有 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 的项目数据时,我得到 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; }
}

最佳答案

[注意:我假设 EF5]

问题可能与您创建 InvoiceInvoiceDetail 实例的方式有关。您正在新建实例,因此它们不是具有延迟加载所有必要组件的 EF 代理。

我建议您尝试使用 DbSet.Create() 方法代替 new

var newInvoice = ctx.Set<Invoice>().Create();
newInvoice.CreationDate = DateTime.Now;
newInvoice.UserId = 14;


var detail1 = ctx.Set<InvoiceDetail>().Create();
detail1.ItemId = 345;
detail1.ItemCount = 10;
newInvoice.InvoiceDetails.Add(detail1);

//...

我不能保证这会解决您的问题,因为 EF 是如此复杂和多变的野兽,但值得一试......

关于c# - 在最近添加的记录中检索导航属性的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17465936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com