Having trouble with foreign key in entity, can't track because the FK is already part of another object

David Craig 31 Reputation points
2020-12-01T00:34:30.12+00:00

Scenario: I have an entity that is central to the business, let's call it Company. Entity Foo has FK CompanyID, as does entity Bar.

If, within the same context, I retrieve Foo and create an instance of Bar, then try _context.Foo.Update(instanceOfFoo), then I get an InvalidOperationException:

The instance of entity type 'Company' cannot be tracked because another instance with the same key value for {'CompanyId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

CompanyID is part of many entities, removing it is a non-starter.

I'm new-ish to EF Core, and would appreciate any suggestions.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
702 questions
{count} votes

Accepted answer
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2020-12-01T05:12:55.133+00:00

    Hi DavidCraig-4984,
    According to your description, maybe your context is being shared by multiple requests which means that the entity you're editing has been tracked already.
    You can try to detach an object that has been attached to the context via setting the state to Detached.
    Code likes below:

    Context.Entry(entity).State = EntityState.Detached  
    

    If you want to load entities from the database without fully attaching them to the context (without change tracking), you can use AsNoTracking as JaliyaUdagedara saide.
    Here are some similar threads you can refer to.
    The instance of entity type cannot be tracked because another instance with the same key value for {'Id'} is already being tracked
    instance of entity type cannot be tracked because another instance with same key value is tracked
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful