Search code examples
linq-to-entitiesentity-framework-core

Delete entities without loading them into memory


In Entity Framework Core I have the following Entity:

public class File {
  public Int32 Id { get; set; }
  public Byte[] Content { get; set; }
  public String Name { get; set; }
}

And I have a list of files ids which I need to delete:

List<Int32> ids = new List<Int32> { 4, 6, 8 }; // Ids example

How can I delete the 3 files without loading each file Content property?

_context.Files.Remove(??);

I do not want to load each file Content property as it is big in size.


Solution

  • EF Core 7 now supports ExecuteUpdate and ExecuteDelete (Bulk updates):

    // Delete all Tags (BE CAREFUL!)
    await context.Tags.ExecuteDeleteAsync();
    
    // Delete Tags with a condition
    await context.Tags.Where(t => t.Text.Contains(".NET")).ExecuteDeleteAsync();
    

    The equivalent SQL queries are:

    DELETE FROM [t]
    FROM [Tags] AS [t]
    
    DELETE FROM [t]
    FROM [Tags] AS [t]
    WHERE [t].[Text] LIKE N'%.NET%'