Mic Got

Mic Got

  • 1.6k
  • 100
  • 7.8k

dbContext tracking error

Jun 18 2023 8:24 AM

Hi,

I have this error on add record event, 'The instance of entity type 'MyRecords' cannot be tracked because another instance with the same key value for {'Field1', 'Field2', 'Field3', 'Field4', 'Field5'} is already being tracked.

All these field are primary key in the table, but i have another field to include that could be null(Field6).

This is the code:

var dbValue = _dbContext.MyRecords.AsNoTracking().Any
                                (x =>
                                 x.Field1 == destinationRecord.Field1 &&
                                 x.Field2 == destinationRecord.Field2 &&
                                 x.Field3 == destinationRecord.Field3 &&
                                 x.Field4 == destinationRecord.Field4 &&
                                 x.Field5 == destinationRecord.Field5 &&
                                 x.Field6 == destinationRecord.Field6);
              
if (dbValue==false)
{                       
    _dbContext.MyRecords.Add(destinationRecord);        
}
else
{                   
    _dbContext.MyRecords.Update(destinationRecord);                  
}

_dbContext.SaveChanges();

The only way i have found is to add an autoincrement primary key but with this filed i can only add record...

Thanks to everyone


Answers (7)