EF Core DB context tracking lifetime and scope

asp.net-core c# dbcontext entity-framework entity-framework-core

Question

I came across some behaviour within ASP.NET Core 2.2 and EF that I'm not sure if it's intended and especially, if it's safe.

Giving the following code:

{ 
    //...

    if (condition)
    {
        var result = await MyDbContext.MyTable
            .Where(data => data.Id == id)
            .FirstOrDefaultAsync();

        result.MyColumn -= 42;
    }

    //...more MyDbContext operations        

    await MyDbContext.SaveChangesAsync();

    //...
}

EF Core successfully queries the database and updates the MyColumn field accordingly (substracting 42 in this case), even tho the result variable declaration and the substraction operation were done in a separate block (and scope implicitly).

Is this an intended and reliable behaviour of how EF operates or it should be avoided and another save operation should be added inside the block?

1
2
1/3/2019 11:39:35 AM

Accepted Answer

This is the intended behavior. All the changes that are made are saved at the DbContext level.

So when you do result.MyColumn -= 42; , you are actually updating the underlying DbContext object which keeps track of all the changes, and knows if an update to the DB is required

2
1/3/2019 11:44:08 AM

Popular Answer

The change tracking is on a per DbContext level, so as long as its the same context used inside of the different scopes, which in your case it seems to be, then this is intended and reliable behaviour yes.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow