Alex P.
Alex P.

Reputation: 3787

EF DbContext: inserted record to table (without SaveChanges()), why can't get it in query?

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

Answers (3)

Wiktor Zychla
Wiktor Zychla

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

Pawel
Pawel

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

zs2020
zs2020

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

Related Questions