21

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?

14
  • 2
    Why would you want to? You have the object already, it's stored as obj1 Dec 6, 2016 at 15:48
  • As soon as you call SaveChanges obj1 will contain anything just saved, such as it's primary key - no need to re-fetch it. Dec 6, 2016 at 15:50
  • @AlfieGoodacre I edited the question to answer you :) Dec 6, 2016 at 15:52
  • @PieroAlberto I'm still confused, you have the object so you can still use it to edit other values Dec 6, 2016 at 15:53
  • @Darren Not necessarily if there are triggers on the database for creationDate or other calculations the object would have to be reloaded in order to get those values. Dec 6, 2016 at 15:53

2 Answers 2

23

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

5
  • 1
    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)))
    – RitchieD
    Dec 22, 2016 at 14:25
  • Can you give an hint here about the "addedEntities"? stackoverflow.com/questions/41982691/… Feb 1, 2017 at 15:42
  • Is there any way you can accomplish this without using ChangeTracker?
    – onhax
    Oct 11, 2018 at 3:12
  • @onhax I don't think there's an easy method. ChangeTracker is what EF uses internally I believe
    – ste-fu
    Oct 12, 2018 at 8:29
  • The Local property of DbSet<T> described in stackoverflow.com/a/8468456/548020 might be a more convenient alternative
    – CodeZombie
    Aug 14, 2019 at 14:50
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.