Hi i have an error only when i try to update the record.
This a console application where i try to copy record from the table Department to the the table DepartmentCopy.
Both tables have a Primary Key.
This is my code:
!----------------------------------------------------------------------------!
using System.Linq;
using CopyRecord.Contexts;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
public class RecordCopyService
{
private readonly DataContext _dbContext;
public RecordCopyService(DataContext dbContext)
{
_dbContext = dbContext;
}
public void CopyRecords()
{
var sourceRecords = _dbContext.Departments.ToList();
foreach (var sourceRecord in sourceRecords)
{
// verify if record exist or not
var dbValue = _dbContext.GetDepartmentCopyById(sourceRecord.DepartmentId);
var destinationRecord = new DepartmentCopy
{
DepartmentCopyId = sourceRecord.DepartmentId,
Name = sourceRecord.Name,
GroupName = sourceRecord.GroupName,
ModifiedDate = sourceRecord.ModifiedDate
};
if (dbValue == null)
{
_dbContext.DepartmentCopies.Add(destinationRecord);
}
else
{
_dbContext.DepartmentCopies.Update(destinationRecord); <-- error here
}
_dbContext.SaveChanges();
}
}
}
!----------------------------------------------------------------------------!
Error details:
The instance of entity type 'DepartmentCopy' cannot be tracked because another instance with the same key value for {'DepartmentCopyId'} is already being tracked.
Thanks for any ideas!
Tuhin PaulPosted Jun 10, 2023, 11:29 AM
Detach the existing tracked entity from the DataContext before updating the record.
By setting the State of the existing tracked entity (dbValue) to EntityState.Detached, you remove it from being tracked by the DataContext.