Project

General

Profile

Bug #373

How to revert changes on detached entities

Added by Victoria Dickerson over 1 year ago. Updated about 1 year ago.

Status:
Closed
Priority:
Normal
Assignee:
-
Category:
-
Target version:
-
Start date:
04/21/2021
Due date:
% Done:

0%

Estimated time:

Description

Here's the flow of the program:

Fetch a list of entities and use them. This will disconnect/detach all entities from the context.
Make changes on one of the entities and save it. I'm loading the entity from the context and apply the changes (scalar properties and relational) of the detached entity to the freshly loaded entity.
I have a feature where the user can revert all changes made on the disconnected entity. Here's the code I'm using: {
using (var db = new TwinTailDb()) {
//Fansubs.Clear();

if (db.Entry(this).State == EntityState.Detached && Id != 0)
{
db.ArchiveEntries.Attach(this);
await db.Entry(this).ReloadAsync();
}
//await db.Entry(this).Collection(a => a.Fansubs).LoadAsync();
}
}
However, when I attach the detached entity, it throws this exception:

Additional information: Attaching an entity of type 'TwinTail.Entities.ArchiveEntry' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Note that the context is automatically disposed because I'm using the using statement.

I'm not sure why it even there is a conflict in the primary key since I didn't even load another entity since the previous context was already disposed.

Also, if I skip step 2 where I save all changes in the entity, it doesn't throw an exception. I'm left with thinking that somehow it's still being tracked .

EDIT: Here's what happens when I skip attaching, proving that the entity is really detached.
myprepaidcenter balance
Additional information: Member 'ReloadAsync' cannot be called for the entity of type 'ArchiveEntry' because the entity does not exist in the context. To add an entity to the context call the Add or Attach method of DbSet.

Seriously, what's happening

#1

Updated by Kentaro Hayashi about 1 year ago

  • Status changed from New to Closed

Also available in: Atom PDF