Reputation: 3787
I have code like this
var context = new MyDbContext(); // db context generated from database
var id = Guid.NewGuid();
var cust = new customer()
{ Id = id, Name = "John" };
context.Customers.Add(cust);
// context.SaveChanges();
var res = context.Customers.Where(c => c.Id == id);
MessageBox.Show(res.Count().ToString());
I inserted a record to a table and when I am running a query I am expecting that result will contain this new record. But in fact it doesn't. It works only if I make SaveChanges() before.
What am I doing wrong, why it doesn't work that way?
Upvotes: 2
Views: 2809
Reputation: 48230
Try to query the local object
http://msdn.microsoft.com/en-us/library/gg696248(v=vs.103).aspx
context.Customers.Local.yourqueryhere
This will query entites tracked by the context, including these which are not yet saved.
Upvotes: 6
Reputation: 31610
You did not insert the record. You just added it to the context on your local box. .SaveChanges()
saves your local data to the database. Since queries always run against the database and you did not call .SaveChanges()
your entity was not returned from the query.
Upvotes: 0
Reputation: 54514
Because var res = context.Customers.Where(c => c.Id == id);
reads from database.
context.Customers.Add(cust);
adds the record in the context only (updating the object graph in EF's context) and context.SaveChanges();
will save it to database.
Upvotes: 3