Hasagiii
Hasagiii

Reputation: 375

Delete all rows from a table with an Entity Framework function using C#

I want to delete all the rows from a table in my SQL Server database (as you can see in the screenshot):

enter image description here

For that I'm using the following function:

private readonly DatabaseContext _context;

[HttpDelete]
public async Task DeleteInstances()
{
    _context.Alertings.RemoveRange();
    await _context.SaveChangesAsync();
}

And in the DbContext I have this:

public class DatabaseContext : DbContext
{
        public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
        {
        }

        public DbSet<AlertingDataModel> Alertings { get; set; }
}

And my AlertingDataModel is:

[Table("Alerting")]
public class AlertingDataModel
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Instance { get; set; }
    public string Serverity { get; set; }
    public string Summary { get; set; }
    public string State { get; set; }
    public string ActiveAt { get; set; }
}

I have done researches, I found this method

context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");

But I think it's an old method, I'm using ASP.NET Core 3.1.1.

If someone could help I'll be so thankful :)

Upvotes: 0

Views: 2197

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89141

Raw SQL is the preferred method to perform bulk changes like this. But the best way to do it otherwise is to fetch all the IDs and construct "Stub Entity" instances with only the IDs populated.

EG

var toDelete = db.Alerts.Select(a => new Alert { Id = a.Id }).ToList();
db.Alerts.RemoveRange(toDelete);
db.SaveChanges();

Upvotes: 4

Related Questions