The instance of entity type cannot be tracked.... I fixed it but I think is a bug.

Discussion of open issues, suggestions and bugs regarding Entity Framework support in ADO.NET Data providers
Post Reply
SamyCode
Posts: 2
Joined: Tue 19 Oct 2021 08:48

The instance of entity type cannot be tracked.... I fixed it but I think is a bug.

Post by SamyCode » Wed 29 Dec 2021 00:26

Hello. I'm trying to do a simple addrange of a list of entities. The complete error reads:

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());
            }

        }
As you can see, I'm even detaching each instance of the entity before inserting, it doesn't work.

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 even forcing ToList() when getting the data just because I read somewhere that iQueryable can produce these types of errors.

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
Last edited by SamyCode on Wed 29 Dec 2021 05:38, edited 1 time in total.

SamyCode
Posts: 2
Joined: Tue 19 Oct 2021 08:48

Re: The instance of entity type 'DSMS_DOCKS_CONCEPT' cannot be tracked.... I'm stuck then.

Post by SamyCode » Wed 29 Dec 2021 02:10

I was able to fix it by changing the DBContext class created by the model wizard as follows:

Code: Select all

modelBuilder.Entity<DSMS_DOCKS_CONCEPT>().Property(x => x.ID_DOCKS_CONCEPTS).HasColumnName(@"ID_DOCKS_CONCEPTS").HasColumnType(@"NUMBER").IsRequired().ValueGeneratedOnAdd();
I changed the last method from ValueGeneratedNever() to ValueGeneratedOnAdd()

Good but this is no way a permanent fix, as I can decide to refresh the DBContext in the Wizard if DB is updated.

I am even more lost because even with the ValueGeneratedNever() instruction for another table, this works:

Code: Select all

public JsonResult PortSave(DSMS_MAIN_PORT portInfo)
        {

            try
            {
                _dbContext.DSMS_MAIN_PORTs.Add(portInfo);
                _dbContext.SaveChanges();
                return Json("Success");
            }
            catch (Exception e)
            {
                return Json("Error: " + e.ToString());
            }
          
        }
In case of inserting just one record with default PrimaryKey value as 0, it seems to insert it correctly and in DB a Primary Key is automatically generated.

Then why it doesn't work in the DSMS_DOCKS_CONCEPT table for addrange method if the Primary Key column is marked as such in both tables??

Is this a bug? Please someone explain.

Shalex
Site Admin
Posts: 9543
Joined: Thu 14 Aug 2008 12:44

Re: The instance of entity type cannot be tracked.... I fixed it but I think is a bug.

Post by Shalex » Tue 04 Jan 2022 17:43

You create Devart EF Core Model (*.efml) via dotConnect for Oracle (Devart.Data.Oracle) provider using Database-First approach with Oracle 19c, don't you?

Entity Developer should set Value Generated=OnAdd for each class property when the corresponding column in the database is created with NUMBER GENERATED ... AS IDENTITY. If you want Entity Developer to generate ValueGeneratedOnAdd() for each NUMBER column, please navigate to Tools > Options > Servers' Options > Oracle and select the "Numeric Primary Key As Identity" checkbox.

Post Reply