Search code examples
c#databaseentity-frameworkprimary-keytracking

solve error "The entity cannot be tracked"


Entities defectmelmaster and defectmeleffectivity have the same primary key.

After forming the lists, I would like to insert these separate lists for defectmelmaster and defectmeleffectivity.

However, after defectmelmaster AddRangeAsync succeeds, defectmeleffectivity AddRange throws an error:

Entity cannot be tracked because same instance ...

Service.cs is where the lists are formed and repo insert methods are called:

foreach (var val in entities)
{
      var defectMelMasterQuery = FormatDefectMelMasterQuery(val, userRegisterId);
      var defectMelEffectivityQuery = FormatDefectMelEffectivityQuery(val, userRegisterId);
}
           
defectMelMasterQueryList.Add(defectMelMasterQuery);
defectMelEffectivityQueryList.Add(defectMelEffectivityQuery);

await _defectMelMasterRepository.InsertDefectMelMaster(defectMelMasterQueryList, cancellationToken);
await _defectMelEffectivityRepo.InsertDefectMelEffectivity(defectMelEffectivityQueryList, cancellationToken); //throws the error

DefectMelEffectivityRepo.cs is where the AddRangeAsync is called and where the error is thrown:

//DefectMelEffectivityRepo

await _dbContext.Set<DefectMelEffectivity>().
            AddRangeAsync(defectMelEffectivityQueryList, cancellationToken);

await _dbContext.SaveChangesAsync(cancellationToken);

Entity class defectmeleffectivityentity.cs:

public void Configure(EntityTypeBuilder<DefectMelEffectivity> builder)
    {
        builder.ToTable("DEFECT_MEL_EFFECTIVITY", schema: "XXX");
        
        builder.Ignore(x => x.Id);
        
        builder.HasKey(f => new {f.AcType, f.AcSeries, 
            f.MelNumber, f.MelSub, f.Ac, f.Company});
    }

Entity class defectmelmasterentity.cs:

public void Configure(EntityTypeBuilder<DefectMelMaster> builder)
    {
        builder.ToTable("DEFECT_MEL_MASTER", schema: "XXX");
        builder.Ignore(x => x.Id);
        builder.HasKey(f => new {f.AcType, f.AcSeries, 
            f.MelNumber, f.MelSub, f.Company});
    }

How can I solve this?


Solution

  • You could try changing state of the entity to Modified:

    _context.Entry(defectmeleffectivity).State = EntityState.Modified; // or  defectmelmaster, whichever is inserted second
    

    This, of course, would need to be implemented correctly in repository, where you have access to DbContext.