Entity framework query on just added but not saved values

Piero Alberto picture Piero Alberto · Dec 6, 2016 · Viewed 11.3k times · Source

I'm using Entity Framework from a couple of years and I have a little problem now.

I add an entity to my table, with

Entities.dbContext.MyTable.Add(obj1);

and here ok.

Then, I'd like to make a query on MyTable, like

Entities.dbContext.MyTable.Where(.....)

The code above will query on my MyTable in the db.

Is there a way to query also on the just added value, before the saveChanges? (obj1) How?

UPDATE

Why do I need this? Because, for each new element I add, I need to edit some values in the previous and the next record (there is a datetime field in this table)

UPDATE2

Let's say I have to add a lot of objects, but I call the saveChanges only after the last item is added. Every time I add the new item, I read its datetime field and I search in the database the previous and the next record. Here, I edit a field of the previous and of the next record. Now, here is problem: if I insert another item, and, for example, the next item is "Obj1", I have to find and edit it, but I can't find it since I haven't saved my changes. Is it clearer now?

Answer

ste-fu picture ste-fu · Dec 6, 2016

You should be able to get your added entities out of the dbContext via the change tracker like this:

 var addedEntities = dbContext.ChangeTracker.Entries()
   .Where(x => x.State == EntityState.Added && x.Entity is Mytable)
   .Select(x => x.Entity as MyTable)
   .Where(t => --criteria--);

Or using the type testing with pattern matching in c# 7.0:

var addedEntities = dbContext.ChangeTracker.Entries()
   .Where(x => x.State == EntityState.Added && x.Entity is Mytable t && --test t for criteria--)
   .Select(x => x.Entity as MyTable);

because you are only querying added entities, you can combine this with

dbContext.MyTable.Where(t => --criteria--).ToList().AddRange(addedEntities);

to get all of the relevant objects