A
A
artshelom2019-02-27 07:05:52
ASP.NET
artshelom, 2019-02-27 07:05:52

How to remove object tracking on save?

I'm trying to update the object, but when updating, I get an error:

The instance of entity type 'Route' cannot be tracked because another instance with the same key value for {'KeyRoute'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

My code:
Route routeOld = _dbContext.Routes.Where(a => a.ApplicationUserId.Equals(user.Id) && a.KeyRoute.Equals(routeSave.KeyRoute)).ToList()[0];//
          _dbContext.SaveChanges();
          if (routeOld == null)
          {
            _dbContext.Routes.Add(routeSave);
          }
          else
          {
            //идет некая проверка между routeOld и routeSave они имеют одинаковый идентификатор
 						_dbContext.Routes.Update(routeSave);
          }
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2019-02-27
@artshelom

Most likely, you manually created a routeSave object with an ID that is already in the database and are trying to add it. If you want to change an existing object, then you first need to get it, but not like this, but this is how you do
it
_dbContext.Routes.FirstOrDefault(a => a ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question