title: How to delete in linq to sql?
body: <p>I am very new to linq to sql and I am not sure how to actually delete a record.</p>
  
  <p>So I been looking at this tutorial</p>
  
  <p><a href="http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx" rel="noreferrer">http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx</a></p>
  
  <p>So for Update they have</p>
  
  <pre><code>NorthwindDataContext db = new NorthwindDataContext();
  
  Product product = db.Products.Single(p =&gt; p.ProductName == "Toy 1");
  
  product.UnitPrice == 99;
  product.UnitsInStock = 5;
  
  db.SubmitChanges();
  </code></pre>
  
  <p>For delete they have</p>
  
  <pre><code>NorthwindDataContext db = new NorthwindDataContext();
  
  var toyProducts = from p in db.Producsts
                where p.ProductName.Contains("Toy")
                    select p;
  
  db.Products.RemoveAll(toyProducts);
  
  db.SubmitChanges();
  </code></pre>
  
  <p>So do I have to query every time, to get the record in order to delete that record? Like I can sort of see doing this with update since you need to give it a record which to update first and then make the changes so I understand the querying part but not with delete.</p>
  
  <p>Like can't you just send in what you want to delete and it goes and deletes it? why do you have to first get it and then tell it to be deleted?</p>
  
  <p>Is that not 2 hits on the database?</p>
  
  <p>Also I have foreign key relationship  that I am trying to get to work. So I have this</p>
  
  <pre><code>public ViewResult(string param1, string param2)
  {
     Table A = new Table A
     A.Field1 = param1;
     A.Field2 = param2;
  
     Delete(A);
  }
  
  private void Delete(Table A)
  {
     DbContext.A.DeleteAllOnsubmit(A.TableB);
     DbContext.A.DeleteAllOnSubmit(A.TableC);
     DbContext.A.DeleteOnSubmit(A);
  
  }
  </code></pre>
  
  <p>So this fails it comes up with this message "Cannot remove an entity that has not been attached."</p>
  
  <p>So I can see why the first 2 lines would fail in the delete method, since I made a new object and their is nothing in the object that has any information about TableB and TableC.</p>
  
  <p>I however can't see why the last line still fails even if the 2 other lines where not there.</p>
  
  <p>Like how I thought it would work it would take my Table A class object that I passed in and look through the table for that information contained in it. It does not seem to be the case though.</p>
  
  <p>So do I first have to take the information out and then do a query to get it and then delete it, like in the example?</p>
  
  <p>Also what is the difference between removeAll() and say DeleteAllOnSubmit().</p>
  
  <p>Like I said I am new to linq to sql and have not been able to sit down and read a book on it due to time constraints. Once I have more time I will read through a book probably.</p>
  
  <p>Thanks</p>