ef core add with child
От: Разраб  
Дата: 30.10.23 09:25
Оценка:
Ошибка
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)] });
☭ ✊ В мире нет ничего, кроме движущейся материи.
Отредактировано 30.10.2023 12:18 Разраб . Предыдущая версия .
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.