实体框架 ToList() 不起作用
我有一些这样的代码:
var db = new MYContext();
var invoice = new Invoice { InvoiceId = 7 };
db.Set<Invoice>().Add(invoice);
var invoiceFound = db.Set<Invoice>().Find(7);
var invoices = db.Set<Invoice>().ToList();
invoiceFound 用发票填充。
问题是发票返回空列表。
有人可以向我解释一下吗?
I have some code like this:
var db = new MYContext();
var invoice = new Invoice { InvoiceId = 7 };
db.Set<Invoice>().Add(invoice);
var invoiceFound = db.Set<Invoice>().Find(7);
var invoices = db.Set<Invoice>().ToList();
invoiceFound gets populated with the invoice.
The problem is invoices is returning an empty list.
Could someone please explain this to me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我没记错的话,调用 ToList() 会调用数据库并返回结果集。由于您在调用 ToList() 之前尚未保存更改(添加发票),因此您添加的发票将不会出现在结果集中。 DbSet 上有一个 Local 属性,它返回内存中的发票集合。即使您不使用 SaveChanges(),此集合也将包含您添加的发票。
If I remember correctly, calling ToList() makes a call to the database and returns the result set. Since you have not saved your changes (add of the invoice) before calling ToList(), the Invoice you added will not be in the result set. There is a Local property on DbSet that returns your in memory collection of Invoices. This collection will contain the Invoice you added even if you don't SaveChanges().
请试试这个:
Please try this one: