Maybe somewhat of an odd use case, but I have a large amount of json that I need to put into a database, but the issue is that there are multiple occurrences of the author
object within the json object that I need to refer to the same author object.
For example:
public class Book
{
public string Title { get; set; }
public string Genre { get; set; }
public Author Author { get; set; }
public List<Author> Reviewers { get; set; }
}
public class Author
{
public string Id { get; set; }
public string Name{ get; set; }
}
// data.json
{
"title": "...",
"genre": "...",
"author": { // Deserializes into Author class
"id": "1"
"name": "..."
},
"reviewers": [ // Deserializes into List<Author>
{
"id": "1", // Needs to point to same object as "author"
"name": "..."
},
{
"id": "2",
"name": "..."
}
]
}
In this example, the authors with the same Id
are deserialized into two different objects when I need them to reference the same object due to Entity Framework Core demanding that no two objects with the same Id can be tracked.
System.InvalidOperationException:
'The instance of entity type 'Author' 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.'