title: Entity Framework updating two tables with one to many relationship
body: <p>I'm using EF code first to control my data. I have two models, <code>ElectricitySite</code> and <code>ElectricitySiteSplit</code>.</p>
  
  <p><code>ElectricitySite</code> contains <code>List&lt;ElectricitySiteSplits&gt; ElectricitySiteSplits</code>, this is a one to many relationship.</p>
  
  <p>I'm trying to write my Update method for the repository layer which will deal with both the tables, so far I have:</p>
  
  <pre><code>public void UpdateElectricitySite(ElectricitySite updatedElectricitySite)
  {
      var dbElectricitySite = GetElectricitySite(updatedElectricitySite.ElectricitySiteId);
  
      _context.ElectricitySites.Attach(updatedElectricitySite);
      _context.Entry(updatedElectricitySite).State = EntityState.Modified;
  
      _context.SaveChanges();
  }
  </code></pre>
  
  <p>I get the following error when I click the Save button:</p>
  
  <blockquote>
    <p>Attaching an entity of type
    'MySolution.Repo.ElectricityModels.ElectricitySiteSplit' failed
    because another entity of the same type already has the same primary
    key value. This can happen when using the 'Attach' method or setting
    the state of an entity to 'Unchanged' or 'Modified' if any entities in
    the graph have conflicting key values. This may be because some
    entities are new and have not yet received database-generated key
    values. In this case use the 'Add' method or the 'Added' entity state
    to track the graph and then set the state of non-new entities to
    'Unchanged' or 'Modified' as appropriate.</p>
  </blockquote>
  
  <p>I think this is because I've not attached my <code>ElectricitySiteSplit</code> entity however if I add this in below my ElectricitySites attachment:</p>
  
  <pre><code>_context.ElectricitySiteSplits.Attach(updatedElectricitySite.SiteSplits);
  </code></pre>
  
  <p>I get this error:</p>
  
  <blockquote>
    <p>Severity  Code    Description Project File    Line    Suppression State
    Error CS1503  Argument 1: cannot convert from
    'System.Collections.Generic.List'
    to 'UtilityBilling.Repo.ElectricityModels.ElectricitySiteSplit'</p>
  </blockquote>
  
  <p>How do I handle the <code>ElectricitySiteSplits</code> table update which is contained in <code>updatedElectrcitiySite.SiteSplits</code> as a list.</p>
  
  <p>FYI - I've already looked here:</p>
  
  <p><a href="https://stackoverflow.com/questions/15336248/entity-framework-5-updating-a-record">Entity Framework 5 Updating a Record</a></p>
  
  <p><a href="https://msdn.microsoft.com/en-gb/data/jj592676.aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-gb/data/jj592676.aspx</a></p>