Информация об изменениях

Сообщение ef core add with child от 30.10.2023 9:25

Изменено 30.10.2023 12:18 Разраб

ef core add with child
Ошибка
The instance of entity type 'Assignee' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.
When attaching existing entities, ensure that only one entity instance with a given key value is attached
из json получаю
class Issue
{
 int id {get;set;}
 Assingee   Assingee {get;set;}
}
class Assingee   
{
 int id {get;set;}
}
...
                db.Issues.Add(entity);


не помню как обойти. Issue новая, Assingee старый
ef core add with child
Ошибка
The instance of entity type 'Assignee' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.
When attaching existing entities, ensure that only one entity instance with a given key value is attached
из json получаю
class Issue
{
 int id {get;set;}
 Assingee   Assingee {get;set;}
}
class Assingee   
{
 int id {get;set;}
}
...
                db.Issues.Add(entity);


не помню как обойти. Issue новая, Assingee старый

   using var tx = db.Database.BeginTransaction();
            foreach (var x in Issue.Issues)
            {
                var person = db.Persons.Find(x.Assignee!.Id);
                if (person != null)
                    db.Entry(person).CurrentValues.SetValues(x.Assignee);
                else
                    db.Add(x.Assignee);
                db.SaveChanges();
                if (db.Issues.Find(x.Id) is Issue issue)
                    db.Entry(issue).CurrentValues.SetValues(x);
                else
                {
                    if (person != null)
                        x.Assignee = person; //<= так заработало, но как-то криво, хотя и логично, может можно лучше?
                    db.Issues.Add(x);
                }
                db.SaveChanges();
            }
            tx.Commit();
            var id = Issue.Issues.MaxBy(x => x.Id).Id + 1;
            Issue.Issues.Add(new Issue { Id = id, Name = $"Issue {id}", Assignee = Person.Persons[Random.Shared.Next(0, 3)] });