AnonyMouse
AnonyMouse

Reputation: 18630

Entity framework ToList() isn't working

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?

Upvotes: 0

Views: 2053

Answers (2)

mekansm
mekansm

Reputation: 73

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().

Upvotes: 1

Gaurang Mistry
Gaurang Mistry

Reputation: 187

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

Upvotes: 0

Related Questions