title: How to properly manage tracking over Entities in LinQ, EF6 and .net 6
body: <p>i have a controller which should save a data from csv to database with some conditions: So half of columns goes to Employees, Children and Spouses tables and the other half of each record goes to Elections table. Elections ID is a string with no autogeneration: it's composed of a letter E, S or C + id of a person.</p>
  <p>When i was trying to just save new information to DB it worked fine, but i need to check if Employee, Child or Spouse already exists, if it exist i just want to update it.</p>
  <p>I'm new to LinQ concepts and i don't really understand the concept of tracking Entities in EF6 and .Net6. Can somebody help me please. Here is my code and exception i'm getting.</p>
  <pre class="lang-cs prettyprint-override"><code>using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.Mvc;
  using System.Net.Http.Headers;
  using System.IO;
  using System.Globalization;
  using System.Linq;
  using CsvHelper;
  using CsvHelper.Configuration;
  using EDI_Manager.TableDefinitions;
  using EDI_Manager.Data;
  using System.Reflection;
  using EDI_Manager.Utilities;
  using Microsoft.EntityFrameworkCore;
  
  namespace EDI_Manager.Controllers
  {
      [Route(&quot;api/[controller]&quot;)]
      [ApiController]
      public class UploadController : ControllerBase
      {
  
          private readonly DataContext _context;
  
          public UploadController(DataContext context)
          {
              _context = context;
          }
  
          [HttpPost, DisableRequestSizeLimit]
          public async Task&lt;IActionResult&gt; Upload()
          {
              try
              {
                  var file = Request.Form.Files[0];
                  var folderName = Path.Combine(&quot;Ressources&quot;, &quot;Files&quot;);
                  var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
  
                  if (file.Length &gt; 0)
                  {
                      var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('&quot;');
                      var fullPath = Path.Combine(pathToSave, fileName);
                      var dbPath = Path.Combine(folderName, fileName);
  
                      using (var stream = new FileStream(fullPath, FileMode.Create))
                      {
                          file.CopyTo(stream);
                      }
  
                      await UploadFileInfo(dbPath);
  
                      return Ok(new { dbPath });
                  }
                  else
                  {
                      return BadRequest();
                  }
              }
              catch (Exception ex)
              {
                  return StatusCode(500, $&quot;Internal server error: {ex}&quot;);
              }
          }
  
          private async Task UploadFileInfo(string path)
          { 
              using var streamReader = new StreamReader(path);
              
              using var csvReeader = new CsvReader(streamReader, CultureInfo.InvariantCulture);
              csvReeader.Context.RegisterClassMap&lt;RecordClassMap&gt;();
  
              var records = csvReeader.GetRecords&lt;Record&gt;();
  
              PropertyInfo[] employeeProperties = typeof(Employee).GetProperties();
              PropertyInfo[] spouseProperties = typeof(Spouse).GetProperties();
              PropertyInfo[] childProperties = typeof(Child).GetProperties();
              PropertyInfo[] electionProperties = typeof(Election).GetProperties();
  
              foreach (var record in records)
              {
                  if (record.RecordType == &quot;Employee&quot;)
                  {
                      int employeeId = -1;
                      string electionId;
                      Employee employee = new();
                      Election employeeElection = new();
                      foreach (var property in employeeProperties)
                      {
                          if (property.Name == &quot;EmployeeId&quot; || property.Name == &quot;SourceFilePath&quot;) continue;
                          property.SetValue(employee, value: record.GetType().GetProperty(property.Name).GetValue(record));
                      }
  
                      employee.SourceFilePath = path;
                      
                      
                      employeeId = (from employees in _context.Employees.AsNoTracking()
                                    where (employees.SourceFilePath == path &amp;&amp; employees.Ssn == employee.Ssn)
                                    select employees.EmployeeId).FirstOrDefault();
                      
  
                      if (employeeId == 0) 
                      {
                          await PostEmployee(employee);
                      }
                      else
                      {
                          employee.EmployeeId = employeeId;
                          await PutEmployee(employeeId, employee);
                      }
                      
                      foreach (var property in electionProperties)
                      {
                          if (property.Name == &quot;ElectionId&quot; || property.Name == &quot;SourceFilePath&quot;) continue;
                          property.SetValue(employeeElection, value: record.GetType().GetProperty(property.Name).GetValue(record));
                      }
  
                      employeeElection.ElectionId = &quot;E&quot; + employeeId;
                      employeeElection.SourceFilePath = path;
  
                      try
                      {
                          electionId = (from elections in _context.Elections.AsNoTracking()
                                        where elections.ElectionId == employeeElection.ElectionId
                                          select elections.ElectionId).Single();
                      }
                      catch (Exception e) {
                          electionId = &quot;&quot;;
                      }
  
                      if (electionId == &quot;&quot;)
                          await PostElection(employeeElection);
                      else
                      {
                          await PutElection(electionId, employeeElection);
                      }
  
                  }
                  else if (record.Relationship == &quot;Spouse&quot;)
                  {
                      int spouseId = -1;
                      string electionId;
                      Spouse spouse = new();
                      Election spouseElection = new();
                      foreach (var property in spouseProperties)
                      {
                          if (property.Name == &quot;SpouseId&quot; || property.Name == &quot;SourceFilePath&quot;) continue;
                          property.SetValue(spouse, value: record.GetType().GetProperty(property.Name).GetValue(record));
                      }
  
                      spouse.SourceFilePath = path;
  
                      
                      spouseId = (from spouses in _context.Spouses.AsNoTracking()
                                  where spouses.SourceFilePath == path &amp;&amp; spouses.Ssn == spouse.Ssn
                                  select spouses.SpouseId).FirstOrDefault();
                      
  
                      if (spouseId == 0)
                      {
                          await PostSpouse(spouse);
                      }
                      else
                      {
                          spouse.SpouseId = spouseId;
                          await PutSpouse(spouseId, spouse);
                      }
  
                      foreach (var property in electionProperties)
                      {
                          if (property.Name == &quot;ElectionId&quot; || property.Name == &quot;SourceFilePath&quot;) continue;
                          property.SetValue(spouseElection, value: record.GetType().GetProperty(property.Name).GetValue(record));
                      }
  
                      spouseElection.ElectionId = &quot;S&quot; + spouseId;
                      spouseElection.SourceFilePath = path;
  
                      try
                      {
                          electionId = (from elections in _context.Elections.AsNoTracking()
                                        where elections.ElectionId == spouseElection.ElectionId
                                        select elections.ElectionId).Single();
                      }
                      catch (Exception e)
                      {
                          electionId = &quot;&quot;;
                      }
  
                      if (electionId == &quot;&quot;)
                          await PostElection(spouseElection);
                      else
                      {
                          await PutElection(electionId, spouseElection);
                      }
  
                  }
                  else if (record.Relationship == &quot;Child&quot;)
                  {
                      int childId = -1;
                      string electionId;
                      Child child = new();
                      Election childElection = new();
                      foreach (var property in childProperties)
                      {
                          if (property.Name == &quot;ChildId&quot; || property.Name == &quot;SourceFilePath&quot;) continue;
                          property.SetValue(child, value: record.GetType().GetProperty(property.Name).GetValue(record));
  
                      }
  
                      child.SourceFilePath = path;
  
                      
                      childId = (from children in _context.Children.AsNoTracking()
                                 where children.SourceFilePath == path &amp;&amp; children.Ssn == child.Ssn
                                 select children.ChildId).FirstOrDefault();
                      
  
                      if (childId == 0)
                      {
                          await PostChild(child);
                      }
                      else
                      {
                          child.ChildId = childId;
                          await PutChild(childId, child);
                      }
  
  
                      foreach (var property in electionProperties)
                      {
                          if (property.Name == &quot;ElectionId&quot; || property.Name == &quot;SourceFilePath&quot;) continue;
                          property.SetValue(childElection, value: record.GetType().GetProperty(property.Name).GetValue(record));
                      }
  
                      childElection.ElectionId = &quot;C&quot; + childId;
                      childElection.SourceFilePath = path;
  
                      try
                      {
                          electionId = (from elections in _context.Elections.AsNoTracking()
                                        where elections.ElectionId == childElection.ElectionId
                                        select elections.ElectionId).Single();
                      }
                      catch (Exception e)
                      {
                          electionId = &quot;&quot;;
                      }
  
                      if (electionId == &quot;&quot;)
                          await PostElection(childElection);
                      else
                      {
                          await PutElection(electionId, childElection);
                      }
                  }
              }
          }
  
          #region HttpPosts
  
  
          [HttpPost]
          [Route(&quot;spouse&quot;)]
          public async Task PostSpouse(Spouse spouse)
          {
              _context.Spouses.Add(spouse);
              await _context.SaveChangesAsync();
          }
  
          [HttpPost]
          [Route(&quot;child&quot;)]
          public async Task PostChild(Child child)
          {
              _context.Children.Add(child);
              await _context.SaveChangesAsync();
          }
  
          [HttpPost]
          [Route(&quot;employee&quot;)]
          public async Task PostEmployee(Employee employee)
          {
              _context.Employees.Add(employee);
              await _context.SaveChangesAsync();
          }
  
          [HttpPost]
          [Route(&quot;election&quot;)]
          public async Task PostElection(Election election)
          {
              _context.Elections.Add(election);
              await _context.SaveChangesAsync();
          }
  
  
          #endregion
  
  
          #region HttpPuts
  
          [HttpPut(&quot;employee/{id}&quot;)]
          public async Task PutEmployee(int id, Employee employee)
          {
              if (id != employee.EmployeeId)
              {
                  return;
              }
  
              _context.Entry(employee).State = EntityState.Modified;
              await _context.SaveChangesAsync();
          }
  
          [HttpPut(&quot;spouse/{id}&quot;)]
          public async Task PutSpouse(int id, Spouse spouse)
          {
              if (id != spouse.SpouseId)
              {
                  return;
              }
              _context.Entry(spouse).State = EntityState.Modified;
              await _context.SaveChangesAsync();
              
          }
  
          [HttpPut(&quot;child/{id}&quot;)]
          public async Task PutChild(int id, Child child)
          {
              if (id != child.ChildId)
              {
                  return;
              }
  
              _context.Entry(child).State = EntityState.Modified;
              await _context.SaveChangesAsync();
          }
  
          [HttpPut(&quot;election/{id}&quot;)]
          public async Task PutElection(string id, Election election)
          {
              if (id != election.ElectionId)
              {
                  return;
              }
  
              _context.Entry(election).State = EntityState.Modified;
              await _context.SaveChangesAsync();
          }
  
          #endregion
  
  
          #region ExistsBooleans
  
          private bool EmployeeExists(int id)
          {
              return _context.Employees.AsNoTracking().Any(e =&gt; e.EmployeeId == id);
          }
  
          private bool SpouseExists(int id)
          {
              return _context.Spouses.AsNoTracking().Any(e =&gt; e.SpouseId == id);
          }
  
          private bool ChildExists(int id)
          {
              return _context.Children.AsNoTracking().Any(e =&gt; e.ChildId == id);
          }
  
          private bool ElectionExists(string id)
          {
              return _context.Elections.AsNoTracking().Any(e =&gt; e.ElectionId == id);
          }
  
          #endregion
  
      }
  }
  </code></pre>
  <p>Exception:</p>
  <pre><code>   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.ThrowIdentityConflict(InternalEntityEntry entry)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(InternalEntityEntry entry)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
     at Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry.set_State(EntityState value)
     at EDI_Manager.Controllers.UploadController.PutChild(Int32 id, Child child) in E:\Courses\EDI_Manager\EDI_ManagerApp\EDI_Manager\Controllers\UploadController.cs:line 330
     at EDI_Manager.Controllers.UploadController.UploadFileInfo(String path) in E:\Courses\EDI_Manager\EDI_ManagerApp\EDI_Manager\Controllers\UploadController.cs:line 223
     at EDI_Manager.Controllers.UploadController.Upload() in E:\Courses\EDI_Manager\EDI_ManagerApp\EDI_Manager\Controllers\UploadController.cs:line 49
  </code></pre>
  <p>If you can give me a hint how to do my task properly. I will apreciate it. Thank you.</p>