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.
开发者_如何学GoCould someone please explain this to me?
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:
var db = new MYContext();
var invoice = new Invoice { ID = 7 };
db.AddToInvoice(invoice);
db.SaveChanges();
var qry = from item in db.Country select item;
IList<Invoice> list = qry.ToList<Invoice>();
精彩评论