Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework query on just added but not saved values

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?

like image 803
Piero Alberto Avatar asked Dec 06 '16 15:12

Piero Alberto


People also ask

How do I save changes in Entity Framework?

Entity Framework Core Save Changes to the database using the SaveChanges method of DbContext. When we use the SaveChanges it prepares the corresponding insert , update , delete queries. It then wraps them in a Transaction and sends them to the database. If any of the queries fails all the statements are rolled back.

How do you get entities back from a query without getting tracked by the context?

The AsNoTracking() extension method returns a new query and returned entities do not track by the context. It means that EF does not perform any additional task to store the retrieve entities for tracking. We can also change the default behavior of tracking at context instance level.

What does AsNoTracking do in Entity Framework?

The AsNoTracking() extension method returns a new query and the returned entities will not be cached by the context (DbContext or Object Context). This means that the Entity Framework does not perform any additional processing or storage of the entities that are returned by the query.

How do I turn off change tracking in Entity Framework?

In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities.


2 Answers

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

like image 99
ste-fu Avatar answered Oct 05 '22 06:10

ste-fu


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

like image 35
Jared Stroebele Avatar answered Oct 05 '22 06:10

Jared Stroebele