Я пытаюсь вставить в свое приложение новое отношение многие ко многим:
У меня есть ресурсы, и я хочу, чтобы у них были зависимости друг от друга.
В свой DbContext я добавил следующий код:
modelBuilder.Entity<Resource>()
.HasMany(e => e.ResourceChildList)
.WithMany(e => e.ResourceParentList)
.Map(m => m.ToTable("LinkResourceResource").MapLeftKey("ResourceIdParent").MapRightKey("ResourceIdChild"));
Это прекрасно создало мою новую таблицу "LinkResourceResource" в базе.
Я добавил ResourceChildList и ResourceParentList
Теперь у меня есть юнит-тест на обновление ресурсов; В этом тесте я создаю 2 ресурса в базе и пытаюсь соединить друг друга в обновлении.
ОТЛАЖИВАТЬ
Когда я вхожу в метод обновления, вот переданный dto:
{Resource}
Id: 487
InternalReference: null
IsDelete: false
Matriculation: null
Name: "Resource Test2"
ResourceChildList: Count = 1
ResourceParentList: Count = 0
ResourceState: Available
ResourceSubtypes: Count = 1
SerialNumber: "Resource Test2"
и вот ребенок в ResourceChildList:
Id: 488
InternalReference: "Child"
IsDelete: false
Matriculation: "child"
Name: "Child"
ResourceChildList: Count = 0
ResourceParentList: Count = 1
ResourceState: Available
ResourceSubtypes: Count = 0
SerialNumber: "Child"
Фактически, когда я прохожу обновление, у меня возникает следующая ошибка:
Failed to attach an entity of type "Entities.Resource" because another entity of the same type already has this primary key value. This can happen when you use the "Attach" method, or you set the status of an entity to "Unchanged" or "Modified" if any features in the chart have conflicting key values. Some entities may be new and may not have received key values generated by the database yet. In this case, use the "Add" method or the "Added" entity to draw the graph, then set the "Unchanged" or "Modified" value to the state of entities other than new entities.
Я провел целый день, пытаясь решить эту проблему, я не понимаю, почему он пытается создать новый ресурс. Кто-нибудь понимает?
Спасибо
РЕДАКТИРОВАТЬ
вот код, используемый для создания / прикрепления
Resource resourceEntity=await Context.Set<Resource>().AsNoTracking().Include(nameof(Resource.ResourceParentList), nameof(Resource.ResourceChildList)).FirstAsync(o => o.Id == 487);
Resource resourceChild= await Context.Set<Resource>().AsNoTracking().Include(nameof(Resource.ResourceParentList), nameof(Resource.ResourceChildList)).FirstAsync(o => o.Id == 488);
resourceEntity.ResourceChildList.Add(resourceChild);
Context.Entry(resourceEntity).State = EntityState.Modified;
await Context.SaveChangesAsync();
Код был бы очень полезен, пожалуйста, также убедитесь, что вы либо прикрепляете ресурс, который вы загрузили с вашим контекстом, либо добавляете правильный идентификатор к свойству.
отредактировал вопрос.
Почему вы загружаете объекты сущностей с помощью AsNoTracking()? Нужен ли в вашем случае сценарий отключения?





Возможно, вам стоит добавить код, в котором вы создаете / прикрепляете и сохраняете объекты