title: Insert Master-Detail with LINQ
body: <p>I want to insert a master-detail with the following structure:</p>
  
  <p>Every Sale has an Id, date and a Client, Employee and SaleDetail.
  Every Sales Detail has a pieces number and price and of course a reference to its master and which product is.</p>
  
  <p>I tried the following code but I cannot get it to work:</p>
  
  <pre><code>private void GenerarNota()
  {
      EntityCollection&lt;SalesDetail&gt; details = new EntityCollection&lt;SalesDetail&gt;();
  
      foreach (ListItem item in _productList)
      {
          SalesDetail detail = new SalesDetail();
          detail.Product = db.Product.FirstOrDefault(p =&gt; p.Id == item.Id);
          detail.Pieces = item.Pieces;
          detail.Price = item.Price;
  
          details.Add(detail);
      }
  
      Sale sale = new Sale
      {
          Client = (Client )txtCliente.Item,
          Employee = (Employee )txtEmp.Item,
          SalesDetail = details
      };
  
      db.AddToSale(sale);
      db.SaveChanges();
  }
  </code></pre>
  
  <p>The exception I got:</p>
  
  <blockquote>
    <p>The object could not be added to the EntityCollection or
    EntityReference. An object that is attached to an ObjectContext cannot
    be added to an EntityCollection or EntityReference that is not
    associated with a source object.</p>
  </blockquote>
  
  <p>Am I doing something wrong? I read about attaching and dettaching objects but after I tried that I got a FK constraint violation.</p>
  
  <p>Can you please tell me what I'm doing wrong or if it's another way to do it? I'm very new at LINQ, I could perfectly do it in pure SQL but I wanted to learn about it.</p>