开发者

Entity framework ToList() isn't working

开发者 https://www.devze.com 2023-04-13 09:12 出处:网络
I have some code like this: var db = new MYContext(); var invoice = new Invoice { InvoiceId = 7 }; db.Set<Invoice>().Add(invoice);

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.

开发者_如何学Go

Could 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>();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号