Entity framework query on just added but not saved values

12,776

Solution 1

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

Solution 2

I think this is a good situation for Transactions. I am going to assume you are using EF 6 since you did not provide a version. =)

UPDATE2 changes

public void BulkInsertObj(List<TEntity> objList)
{
    using (var context = new dbContext()) 
    { 
        using (var dbContextTransaction = context.Database.BeginTransaction()) 
        {  
            try 
            { 
                foreach(var obj1 in objList)
                {
                    dbContext.MyTable.Add(obj1);

                    //obj1 should be on the context now 
                    var previousEntity = dbContext.MyTable.Where(.....) //However you determine this
                    previousEntity.field = something

                    var nextEntity = dbContext.MyTable.Where(.....) //However you determine this
                    nextEntity.field = somethingElse
                }

                context.SaveChanges(); 
                dbContextTransaction.Commit(); 
            } 
            catch (Exception) 
            { 
                dbContextTransaction.Rollback(); 
            } 
        } 
    } 
}

MSDN EF6 Transactions

Share:
12,776
Piero Alberto
Author by

Piero Alberto

Web developer. Internet addicted, loves the web and its world.

Updated on June 07, 2022

Comments

  • Piero Alberto
    Piero Alberto almost 2 years

    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?

  • RitchieD
    RitchieD over 7 years
    This is good solution. However it did not work for me, as is. In my case the Entity.GetType().Name was appended with a GUID. So I consider the BaseType as well. Where(x => x.State == EntityState.Added && (x.Entity.GetType() == typeof(MyTable) || x.Entity.GetType().BaseType == typeof(MyTable)))
  • Piero Alberto
    Piero Alberto over 7 years
    Can you give an hint here about the "addedEntities"? stackoverflow.com/questions/41982691/…
  • onhax
    onhax over 5 years
    Is there any way you can accomplish this without using ChangeTracker?
  • ste-fu
    ste-fu over 5 years
    @onhax I don't think there's an easy method. ChangeTracker is what EF uses internally I believe
  • CodeZombie
    CodeZombie over 4 years
    The Local property of DbSet<T> described in stackoverflow.com/a/8468456/548020 might be a more convenient alternative