3

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?

0

2 Answers 2

3

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

1

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.

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.