title: EF Core: The instance of entity type cannot be tracked and context dependency injection
body: <p>I am developing an app that should manage teambuildings, and I am using .NET Core and EF Core for my backend, together with Autofac for dependency injection. In my page, after I get all my teambuildings in a list from the backend, and then I try to modify the values for one of them, I get the following error:</p>
  
  <blockquote>
    <p>The instance of entity type 'TeamBuilding' cannot be tracked because another instance with the same key value for {'Id'} 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</p>
  </blockquote>
  
  <p>Here are the classes and methods I use:</p>
  
  <p>Controller</p>
  
  <pre><code>    [Produces("application/json")]
      [Route("api/teamBuildings")]
      public class TeamBuildingController : Controller
      {
          public ITeamBuildingService _service;
  
          public TeamBuildingController(ITeamBuildingService serviceTeam)
          {
              _service = serviceTeam;
          }
  
          [HttpPost]
          public IActionResult Create([FromBody]TeamBuildingForCreationDto teamBuilding)
          {
              try
              {
                  var existingTb = _service.GetByID(teamBuilding.Id);
                  if (existingTb != null)
                  {
                      return BadRequest("An entry with this id already exists");
                  }
  
                  _service.Create(teamBuilding);
                  return Ok();
              }
              catch (Exception ex)
              {
                  return BadRequest(ex.Message);
              }
          }
  
          [HttpGet]
          public IActionResult GetAll()
          {
              var teamBuildings = _service.GetAll();
              if (teamBuildings == null)
              {
                  return NotFound("There are no team buidings");
              }
              return Ok(teamBuildings);
          }
  
          [HttpGet("{id}")]
          public IActionResult GetTeambuilding(int id)
          {
              var teamBuilding = _service.GetByID(id);
              if (teamBuilding == null)
              {
                  return NotFound("There is no team buiding with such an ID");
              }
              return Ok(teamBuilding);
          }
  
          [HttpPut]
          public IActionResult UpdateTeamBuilding([FromBody]TeamBuildingViewModel viewModel)
          {
              try
              {
                  var existingTeamBuilding = _service.GetByID(viewModel.Id);
                  if (existingTeamBuilding == null)
                  {
                      return NotFound("There is no team buiding with such an ID");
                  }
  
                  _service.UpdateTeamBuilding(viewModel);
                  return Ok();
              }
              catch (Exception ex)
              {
                  return BadRequest(ex.Message);
              }
          }
      }
  </code></pre>
  
  <p>Service</p>
  
  <pre><code>public class TeamBuildingService : ITeamBuildingService
      {
          private IGenericRepository&lt;DAL.Models.TeamBuilding&gt; _repositoryTeam;
  
          public TeamBuildingService(IGenericRepository&lt;DAL.Models.TeamBuilding&gt; repositoryTeam)
          {
              _repositoryTeam = repositoryTeam;
          }
  
          public TeamBuildingDetailsViewModel GetByID(int id)
          {
              var teamBuilding = _repositoryTeam.GetByID(id);
              var viewModel = Mapper.Map&lt;TeamBuildingDetailsViewModel&gt;(teamBuilding);
              return viewModel;
          }
  
          public IEnumerable&lt;TeamBuildingViewModel&gt; GetAll()
          {
                //code which returns all the teambuilding from the database, omitted on purpose
          }
  
  
          public TeamBuildingViewModel UpdateTeamBuilding(TeamBuildingViewModel teamBuildingViewModel)
          {
              var teamBuilding = Mapper.Map&lt;DAL.Models.TeamBuilding&gt;(teamBuildingViewModel);
  
              _repositoryTeam.Edit(teamBuilding);
              _repositoryTeam.Commit();
              return teamBuildingViewModel;
          }
      }
  }
  </code></pre>
  
  <p>Repository</p>
  
  <pre><code>public class GenericRepository&lt;T&gt; : IGenericRepository&lt;T&gt; where T : class
      {
          public DbContext _context;
          public DbSet&lt;T&gt; dbset;
  
          public GenericRepository(DbContext context)
          {
              _context = context;
              dbset = context.Set&lt;T&gt;();
          }
  
          public IQueryable&lt;T&gt; GetAll()
          {
              return dbset;
          }
  
          public T GetByID(params object[] keyValues)
          {
              return dbset.Find(keyValues);
          }
  
          public void Edit(T entity)
          {
              _context.Entry(entity).State = EntityState.Modified;
          }
  
          public void Insert(T entity)
          {
              dbset.Add(entity);
          }
  
          public void Delete(T entity)
          {
              _context.Entry(entity).State = EntityState.Deleted;
          }
  
          public T GetByFunc(Func&lt;T, bool&gt; func)
          {
              return dbset.AsQueryable().Where(x =&gt; func(x)).FirstOrDefault();
          }
  
          public void Commit()
          {
              _context.SaveChanges();
          }
      }
  </code></pre>
  
  <p>The Dependency Injection part</p>
  
  <pre><code>        var builder = new ContainerBuilder();
          builder.Populate(services);
  
          builder.RegisterType&lt;UserController&gt;();
          builder.RegisterType&lt;TeamBuildingController&gt;();
          builder.RegisterType&lt;UserService&gt;().As&lt;IUserService&gt;();
          builder.RegisterType&lt;TeamBuildingService&gt;().As&lt;ITeamBuildingService&gt;();
          builder.RegisterType&lt;TeamBuildingContext&gt;().As&lt;DbContext&gt;().InstancePerLifetimeScope();
  
          builder.RegisterGeneric(typeof(GenericRepository&lt;&gt;))
              .As(typeof(IGenericRepository&lt;&gt;));
  
          this.ApplicationContainer = builder.Build();
  
          // Create the IServiceProvider based on the container.
          return new AutofacServiceProvider(this.ApplicationContainer);
  </code></pre>
  
  <p>To detail the problem more exactly, I do the following things:</p>
  
  <ul>
  <li><p>make a GET request to get all the teambuildings</p></li>
  <li><p>from the same browser, server instance and immediately after, I try to modify some of the fields on a random teambuilding by making a PUT request</p></li>
  <li><p>I get the error shown above</p></li>
  </ul>
  
  <p>I know one of the solutions is to get the object I want to update from the database first , then on that object to modify its fields with the new values, then pass it to the update function. </p>
  
  <p>But shouldn't the request, according to my code, create a new context, then after the request is done and the response was given to the client the context to be disposed, and for a new request a completely new context that has no information about the previous one be created? As I see it now, I create a context with the GET request, then the context is reused by the PUT request, hence the "Cannot be tracked" error. </p>
  
  <p>What am I doing wrong, and if everything is actually ok, is the method of getting the object after the Id first the good practice?</p>