question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Additional information: The instance of entity type ... cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values.

See original GitHub issue

I have a generic repository implemented in a class library all CRUD methods except works _dbSet.Remove(entity);

The instance of the object is defined as AddScope.

Could someone help me

An exception of type ‘System.InvalidOperationException’ occurred in EntityFramework.Core.dll but was not handled in user code

Additional information: The instance of entity type ‘TMS.Domain.Entities.Pais’ cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values.

public class RepositoryBase<TEntity> : IRepositoryBase<TEntity> where TEntity : class
{

    private IAppDbContext _dbContext;
    protected DbSet<TEntity> _dbSet;


    public RepositoryBase(IAppDbContext dbContext)
    {
        _dbContext = dbContext;
        _dbSet = _dbContext.Set<TEntity>();
    }

    //public RepositoryBase()
    //{
    //    _dbContext = new AppDbContext();
    //    _dbSet = _dbContext.Set<TEntity>();
    //}

    public virtual IEnumerable<TEntity> GetAll()
    {
        return _dbSet.ToList();
    }

    public IEnumerable<TEntity> GetAllAsReadOnly()
    {
        return _dbSet.AsNoTracking();
    }

    public virtual IEnumerable<TEntity> GetBy(Expression<Func<TEntity, bool>> filter)
    {
        return _dbSet.Where(filter);
    }

    public IQueryable<TEntity> GetQueryBy(Expression<Func<TEntity, bool>> filter)
    {
        return _dbSet.Where(filter);
    }

    public virtual void Create(TEntity entity)
    {
        _dbSet.Add(entity);
    }

    public virtual void Edit(TEntity entity)
    {
        _dbSet.Update(entity);
    }

    public virtual void Delete(TEntity entity)
    {
        _dbSet.Remove(entity);
    }

    public int Save()
    {
        return _dbContext.SaveChanges();
    }

    public void Dispose()
    {
        //_dbContext.Dispose();
        GC.SuppressFinalize(this);
    }

    public TEntity FindBy(Expression<Func<TEntity, bool>> filter)
    {
        return _dbSet.Where(filter).SingleOrDefault();
    }

    public TEntity FindAsReadOnlyBy(Expression<Func<TEntity, bool>> filter)
    {
        return _dbSet.Where(filter).AsNoTracking().SingleOrDefault();
    }

    public void Delete(Expression<Func<TEntity, bool>> filter)
    {
        TEntity entity = _dbSet.Where(filter).SingleOrDefault();
        _dbSet.Remove(entity);
    }
}

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
gilmaremncommented, Nov 25, 2015

It worked perfect with AsNoTracking ();

Thank you!

1reaction
rowanmillercommented, Nov 24, 2015

Hey,

Looking at your code, I think it’s these lines of code in PaisesController.cs that are causing your issue…

141                 PaisViewModel paisViewModel = _paisApp.GetBy(id).SingleOrDefault(); 
142 
143                 ValidationResultApp result = _paisApp.DeleteValidation(paisViewModel); 

The “query for an instance and then mark as deleted” pattern you are doing is good, the problem is that because of the various layers of abstraction you don’t end up marking the actual entity instance as deleted, you attempt to tell the context that a new instance of the entity is deleted… but it has the same primary key value that was created when you queried for the entity from the database.

There are two options here:

  • Update the repository to lookup the existing entity (based on the key values of the entity passed to the Delete method) and mark it as deleted.
  • Use the AsNoTracking() method whenever you retrieve data, this avoids having the entities be tracked by the context and frees you up to re-attach new instances when you want to update/delete.
Read more comments on GitHub >

github_iconTop Results From Across the Web

The instance of entity type cannot be tracked because ...
The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked ·...
Read more >
instance of entity type cannot be tracked because ... - YouTube
instance of entity type cannot be tracked because another instance with same key value is tracked - EF Core.
Read more >
Having trouble with foreign key in entity, can't track ...
The instance of entity type 'Company' cannot be tracked because another instance with the same key value for {'CompanyId'} is already being ......
Read more >
How do I fix: the instance of entity type sometype cannot be ...
The instance of entity type SomeType cannot be tracked because another instance with the same key value for SomeField is already being ......
Read more >
cannot be tracked because another instance with the same ...
Error : The instance of entity type 'Address' cannot be tracked because another instance with the same key value for {'Id'} is already...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found