Entity Framework FromSqlInterpolated examples

The FromSqlInterpolated method in Entity Framework Core is used to execute a raw SQL query that contains interpolated parameters.

Interpolated parameters are replaced with actual values at runtime, which helps to protect against SQL injection attacks.

The following code shows how to use the FromSqlInterpolated method to execute a raw SQL query which searches for a customer via their email:

And from the resulting SQL we see that Entity Framework has replaced the email variable with a parameter :


FromSqlInterpolated is particularly useful for complex SQL queries that might be cumbersome with LINQ. For simple queries like the example above, using LINQ would be preferable, both for safety and for leveraging the benefits of Entity Framework.

A slightly more complex example is shown below …

Use raw SQL with caution

If you use FromSqlInterpolated (or any other method that allows raw SQL) inappropriately or without understanding its potential vulnerabilities, it can introduce security risks to your application. Always ensure you know what the SQL is doing and be aware of the potential for SQL injection.

The FromSqlInterpolated method ensures that the interpolated variables are parameterized, mitigating the risk of SQL injection but as always, it’s still essential to validate and sanitize input data.

Leave a Reply

Your email address will not be published. Required fields are marked *