When I am trying to insert/update the records I am getting the below error.
The instance of entity type cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.
Below is my code for the same. Here I am creating/generating the ID(Primary Key) by increment with 1. I am getting error at both Save & Update
public bool SaveDataCapDetails(List<TDataCapDetails> lstDataCapDetails)
{
bool IsSuccess = false;
using (var dbContextTransaction = _objContext.Database.BeginTransaction())
{
try
{
List<TDataCapDetails> lstDataCapDetailsRecords = null;
if (lstDataCapDetails.Where(x => x.Id == 0).Count() > 0)
{
lstDataCapDetailsRecords = new List<TDataCapDetails>();
lstDataCapDetailsRecords.InsertRange(0, lstDataCapDetails);
int? id = _objContext.TDataCapDetails.Max(x => (int?)x.Id);
id = id == null ? 0 : id;
foreach (var item in lstDataCapDetailsRecords.Where(x => x.Id == 0))
{
id = id + 1;
item.Id = (int)id;
}
_objContext.Entry(lstDataCapDetailsRecords).State = EntityState.Detached;
_objContext.AddRange(lstDataCapDetailsRecords);
_objContext.SaveChanges();
}
if (lstDataCapDetails.Where(x => x.Id > 0).Count() > 0)
{
lstDataCapDetailsRecords = new List<TDataCapDetails>();
lstDataCapDetailsRecords = lstDataCapDetails.Where(x => x.Id > 0).ToList();
_objContext.UpdateRange(lstDataCapDetailsRecords);
_objContext.SaveChanges();
}
dbContextTransaction.Commit();
}
catch (Exception ex)
{
dbContextTransaction.Rollback();
throw ex;
}
}
return IsSuccess;
}
The above method I am calling from business layer like below
bool success = dal.SaveDataCapDetails(lstDataCapDetails)
I have tried with AsNoTracking and other options available, but still I am not able to resolve this issue.
Any help on this appreciated.

Attach(). I don't sure if you can do_objContext.Attach(lstDataCapDetails), but at least you should attach to existing_objContextand setHasIndex()withIsUnique()for any unique indexes.