5

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 Answer 1

9

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);
2
  • can the query have "Begin Transaction; DELETE from Table1; Delete From Table2; End Transaction" Sep 8, 2022 at 13:46
  • 1
    So long as that's legal in your database, sure. Sep 8, 2022 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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