0

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 :)

4
  • 3
    But I think it's an old method ← Why? Depending on the number of records in the table you want to empty using a pure EF approach might be just fine but you have to retrieve the records and then delete them. If the table can contain many records then either a DELETE FROM or TRUNCATE TABLE would be preferred.
    – Igor
    Mar 23, 2020 at 20:09
  • I think it's not good using the direct sql execute? That's what I was told, I was looking for a function like the one given by @David
    – Hasagiii
    Mar 23, 2020 at 20:25
  • Raw sql will be more performant but that might not matter at all if the number of records in the table is limited. What you choose should be based on what you need and what you expect the table to contain.
    – Igor
    Mar 23, 2020 at 20:28
  • I'll have a lot of recording cocerning this history of Alerting , now I have to create a BackGround Service that keeps calling the Add method, I think I'll be using a timer of 5mins maybe, I dont know if it's opt and I dont know how to use these background services neither, anyway I'll go read the documentation, thanks for your help :)
    – Hasagiii
    Mar 23, 2020 at 20:42

1 Answer 1

4

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();
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.