The instance of entity type 'DSMS_DOCKS_CONCEPT' cannot be tracked because another instance with the same key value for {'ID_DOCKS_CONCEPTS'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
If you do a Google search, you will find tons, and I mean tons of answers for this problem. However nothing will resolve my issue.
Take this SO link for example: https://stackoverflow.com/questions/482 ... h-same-key
First solution: Make your DBContext scoped instead of Singleton
As far as I know, the AddDbContext service on Startup does just that.
Second solution: Detach the entity from tracking.
I did. Same error. Moreover, I don't really think that entity in particular is been tracked anyway, as that entity is not related to any other table. Yes, it has an id to another table but a real relationship is not forced in the DB.
I deleted everything from my controller and this is the minimum code that will reproduce the error:
Code: Select all
[HttpPost]
public JsonResult DockUpdate(DocksAdminData dockInfo)
{
var concepts = new List<DSMS_DOCKS_CONCEPT>();
foreach (var item in dockInfo.Concepts.Select((value, i) => new { i, value }))
{
concepts.Add(new DSMS_DOCKS_CONCEPT { ID_DOCK = dockInfo.Id, CONCEPT = item.value });
_dbContext.Entry(concepts[item.i]).State = Microsoft.EntityFrameworkCore.EntityState.Detached;
}
try
{
_dbContext.DSMS_DOCKS_CONCEPTs.AddRange(concepts);
_dbContext.SaveChanges();
return Json("Success");
}
catch (Exception e)
{
return Json("Error: " + e.ToString());
}
}
I have tried other several solutions. I even disabled tracking when I read those concepts from the db when the page loads just in case, as shown here:
Code: Select all
[HttpGet]
public JsonResult ConceptsByDocksGet(decimal dockId)
{
return Json(_dbContext.DSMS_DOCKS_CONCEPTs.Where(dc => dc.ID_DOCK == dockId)
.Select(r => r.CONCEPT).AsNoTracking().ToList());
}
I'm using DB First approach with Devart model.
The problematic property is a primary key, and I'm passing 0 as a value because it should get generated in DB.
I'm really stuck and I'm starting to think this is a Devart bug or something.
Can someone help? I will REALLY appreciate it.
Thank you