title: Deleting multiple records with Entity Framework using a single LINQ query
body: <p>I'm trying to perform a DELETE using LINQ that will generate a single query.</p>
  
  <p>Here's how I'm doing it:</p>
  
  <pre class="lang-cs prettyprint-override"><code>// NorthwintEntities is an ADO.NET Entitity Data Model
  var northwindEntities = new NorthwindEntities();
  northwindEntities.Order_Details.Delete(o =&gt; o.Order_ID == 11076);
  </code></pre>
  
  <p>Here's my Extension:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public static class EntityExtensions
  {
      private static Regex rxTableName = new Regex(@"^FROM\s+(?&lt;table&gt;\[[^\]]*\](\.\[[^\]]*\]){0,2})\s+AS\s+(?&lt;alias&gt;\[[^\]]*\])", RegexOptions.Multiline);
  
      public static void Delete&lt;T&gt;(this ObjectSet&lt;T&gt; entity, Expression&lt;Func&lt;T, bool&gt;&gt; expression) where T : EntityObject
      {
          var selectQuery = entity.Where(expression).Select(x =&gt; 1);
  
          string selectQueryString = ((ObjectQuery)selectQuery).ToTraceString();
  
          string deleteQueryString = ConvertSqlSelectToDelete(selectQueryString);
  
          entity.Context.ExecuteStoreCommand(deleteQueryString);
      }
  
      private static string ConvertSqlSelectToDelete(string selectQuery)
      {
          if (selectQuery.IndexOf(" JOIN ") &gt; -1)
          {
              throw new Exception("Query with JOIN is not supported: " + selectQuery);
          }
  
          Match match = rxTableName.Match(selectQuery);
          if (!match.Success)
          {
              throw new Exception("Unable to convert SELECT: " + selectQuery);
          }
  
          string deleteQuery = "DELETE \r\n" + selectQuery.Substring(match.Index);
          deleteQuery = deleteQuery.Replace(match.Groups["alias"].Value + ".", "");
          deleteQuery = deleteQuery.Replace("AS " + match.Groups["alias"].Value, "");
  
          return deleteQuery;
      }
  }
  </code></pre>
  
  <p>This works, but I have a few comments.</p>
  
  <ul>
  <li>I'm not a big fan of using Regex here, but it was the only way for me to get the table name. (entity.EntitySet.Name wouldn't always return the correct name.  [Order Details] is a an example).</li>
  <li>After completing this, I found this <a href="http://msmvps.com/blogs/matthieu/archive/2010/05/21/bulk-delete-v3.aspx">http://msmvps.com/blogs/matthieu/archive/2010/05/21/bulk-delete-v3.aspx</a>  but couldn't get it to work anyway.  Kept getting a NotImplementedException from the context being null.</li>
  <li>Delete with join's doesn't seem to work.  I'm testing with SQL Server Compact 3.5, maybe it's a limitation of that.</li>
  </ul>
  
  <p><strong>So my questions is: Is there an easier way to do this?  If so, what is it?</strong></p>
  
  <p>Any help at all will be appreciated.</p>