Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug Report: Unexpected Behavior When Removing Non-Tracked Entities in Entity Framework #35188

Open
pouryax7x opened this issue Nov 23, 2024 · 1 comment

Comments

@pouryax7x
Copy link

pouryax7x commented Nov 23, 2024

Hello,

I encountered an issue with the following scenario in my code:

Code Snippet:

public void RemoveUser(User user)
{
    try
    {
        _myContext.User.Remove(someUser); // Attempting to remove a user
        _myContext.SaveChanges();
    }
    catch (Exception ex)
    {
        // Exception happens in Attempting to remove a user because user did not exist
        // And SaveChanges not called
        // Log the exception
    }
}

Problematic Usage:

I called RemoveUser in a foreach loop without first verifying if the user exists in the database:

foreach (var user in userList)
{
    RemoveUser(user); // No check if the user exists in the database
}

After the foreach loop, I added a new user and saved changes to the database.

Observed Behavior:

To my surprise, I discovered 16 users in the database instead of the expected count.

Investigation:

Upon reviewing the code, I realized the issue: when attempting to remove users that do not exist in the database and are not being tracked by the DbContext, Entity Framework seems to treat these entities as new entities. As a result, when SaveChanges is called after the loop, all these non-existent users are inserted into the database instead of being ignored or flagged as errors.

Expected Behavior:

I expected one of the following behaviors:

  1. A runtime error indicating that the entity does not exist in the database or is not being tracked.
  2. Entity Framework ignoring such remove operations without treating them as inserts.

Is this the intended behavior, or is there a way to avoid this issue programmatically? Should I be explicitly checking the entity state before removing users?

Thank you for your guidance!

@ajcvickers
Copy link
Member

This issue is lacking enough information for us to be able to fully understand what is happening. Please attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants