Mic Got

Mic Got

  • 1.6k
  • 100
  • 8k

DbContext update failed

Jun 10 2023 9:45 AM

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!

 


Answers (1)