Отсоединение сущности контекста - PullRequest
1 голос
/ 16 июня 2020

У меня вопрос по отключению контекста. При повторном редактировании строки в таблице Задачи возникает ошибка выполнения в строке «context.Tasks.Attach (selectedTask);». Как я могу отсоединить его или обойти эту ошибку?

private void btnOK_Click(object sender, EventArgs e)
        {
            using (var context = new ProjectManagementEntities())
            {
                string title = txtTitle.Text;
                string description = txtDescription.Text;
                DateTime dueDate = dtpDueDate.Value.Date;
                Category category = cmbCategory.SelectedItem as Category;
                Status status = cmbStatus.SelectedItem as Status;

                context.Categories.Attach(category);
                context.Status.Attach(status);
                context.Tasks.Attach(chosenTask);

                chosenTask.Title = title;
                chosenTask.Description = description;
                chosenTask.DueDate = dueDate;
                chosenTask.Category = category;
                chosenTask.Status = status;

                context.SaveChanges();
            }

            Close();
        }

Изменить: выбрано исключение:

System.InvalidOperationException: 'Attaching an entity of type 'ProjectManagement.Status' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.'
...