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

ChangeTracker and the results of deserializing data of tree-like structures #26977

Closed
sergeykorobeynikov opened this issue Dec 13, 2021 · 2 comments

Comments

@sergeykorobeynikov
Copy link

We are using generic entity classes for JSON deserialization and Entity Framework Core 6.

Here is an example of two related entities:

public class Vendor
{
	public int Id { get; set; }
	public string Name { get; set; }
	public ICollection<Category> Categories { get; set; }
}

public class Category
{
	public int Id { get; set; }
	public string Name { get; set; }
	public int? ParentId { get; set; }
	[ForeignKey(nameof(ParentId))]
	public Category Parent { get; set; }
}

When deserializing JSON data from a provider, there may be a situation where there will be two instances of the same object type with the same identifiers (Id).

As a result, data manipulation may result in an error:

System.InvalidOperationException: "The instance of entity type 'Category' cannot be tracked because another instance with the key value '{id: 1}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached."

At the same time, attempts to disable tracking do not lead to anything:
db.ChangeTracker.AutoDetectChangesEnabled = false;

It is possible to solve this problem by creating a separate dictionary for the data type, and using the key to "reassign" the correct instances, but this is very difficult for tree-like structures.

Is this some kind of flaw or is there a solution to this problem?

@ajcvickers
Copy link
Member

@sergeykorobeynikov See Identity Resolution in EF Core and make sure to vote (👍) for #20124, which should make this easier.

@sergeykorobeynikov
Copy link
Author

Like with respect! Now it is clear why references in JSON and XML are needed!

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
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

2 participants