title: EF how to update entity containing the List of entities
body: <p>I have a class Device as follows.</p>
  
  <pre><code>public class Device
  {
      public string id { get; set; }
      public string name { get; set; }
      public List&lt;Instructions&gt; Instructions { get; set; }
  }
  </code></pre>
  
  <p>Now I have a view which has sections related to device and provision to add Instrunctions to the device. </p>
  
  <p>If the device is new then <code>this.context.Devices.Add(device)</code> is working fine.</p>
  
  <p>but if I want to edit the device. I find it by Id. It is populated. and if I change the  individual property then it is running fine. but I want to update the whole device at once which is not happening. </p>
  
  <p>My sample code is as follows.</p>
  
  <pre><code>public async Task&lt;bool&gt; AddInstrument(Device device)
  {
      try
      {
          var newDevice = this.context.Device
                          .Where(i =&gt; i.Id == device.Id).FirstOrDefault();//  i tried find,single or default also
  
          //adding new device
          if (newDevice == null)
          {
              this.context.Device.Add(device);
              return await this.context.SaveChangesAsync() &gt; 0;
          }
  
          //if editing the device
          newDevice = device;
          return await this.context.SaveChangesAsync() &gt; 0;
      }
      catch
      {
          throw;
      }
  } 
  </code></pre>
  
  <p>what I want to achieve.</p>
  
  <p>problem :- I want to update the corresponding device in the database. along with the instructions. 
  e.g. Previously a device named "D22" has 3 instructions (a1,a2,a3). </p>
  
  <p>but now same device has values name "D22_1" and now instructions are a1,a3(updated any field),a2(deleted). b1 &amp; a4 are added so after editing the fields I have Instructions as a1,a2,b1,b4 for D22_1 .</p>
  
  <p>My effort:- </p>
  
  <p>What I have tried.</p>
  
  <p>1) For main device D22 if I specify properties explicitly it is fine e.g. </p>
  
  <pre><code>device.Name="aaaaa";
  
  this.context.savechanges();
  </code></pre>
  
  <p>reflects it in database. I have not tried this for updating Instructions in List.</p>
  
  <p>2)I tried to use </p>
  
  <pre><code>this.context.Entry(device).State = EntityState.Modified;
  </code></pre>
  
  <p>but with various hit and trial I could not run it. The best I could get is this error  " 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 .."</p>
  
  <p>Please suggest me something. Moreover I want to know about various techniques related to updating entries with list in EF. I assume EF will automatically take care of the child object (i.e. addition/updation and deletion).
  In my case Instructions for device.</p>