How to delete records with FromSqlRaw in ASP.NET Core 5?

Viewed 1668

I am trying to delete all records in a PostgresSQL database table from ASP.NET Core 5.

However, I get this error:

syntax error at or near "FROM"

This is my code:

string Query = "DELETE FROM public.\"MyTable\"";
var d = await _context.MyTable.FromSqlRaw(Query).AnyAsync();

How to delete records with FromSQLRaw?

1 Answers

DbSet<T>.FromSqlRaw is for fetching entities with SQL. To run an arbitrary command use Database.ExecuteSqlRaw. eg

string query = "DELETE FROM public.MyTable";
var rowCount = await _context.Database.ExecuteSqlRawAsync(query);
Related