Skip to main content

How do you execute raw SQL queries in EF Core?

Mid ASP.NET Web API
Quick Answer Raw SQL in EF Core: context.Database.ExecuteSqlRawAsync("DELETE FROM Logs WHERE CreatedAt < {0}", cutoff) for commands. context.Users.FromSqlRaw("SELECT * FROM Users WHERE Name = {0}", name) for queries (still tracked). Use parameterized queries (not string concatenation) to prevent SQL injection. Return mapped entities with FromSqlRaw, anonymous types with Dapper alongside EF Core.

Answer

Use:

  • FromSqlRaw() for queries
  • ExecuteSqlRaw() for commands

Always use parameters to prevent SQL injection.

S
SugharaIQ Editorial Team Verified Answer

This answer has been peer-reviewed by industry experts holding senior engineering roles to ensure technical accuracy and relevance for modern interview standards.

Want to bookmark, take notes, or join discussions?

Sign in to access all features and personalize your learning experience.

Sign In Create Account

Source: SugharaIQ

Ready to level up? Start Practice