I was pair programming with a team member when she got the following compiler error:
Error CS1503 Argument 2: cannot convert from 'string' to 'System.FormattableString'
The error appeared after trying to compile the following code:
The reason becomes apparent when we look at the signature of the SqlQuery
method:
As you can see the method expects a FormattableString
not a string
. Why is this?
By using a FormattableString
EF Core can protect us from SQL injection attacks. When we use this query with parameters(through string interpolation), the supplied parameters values are wrapped in a DbParameter
.
To get rid of the compiler error, we can do 2 things:
1. We explicitly create a FormattableString
from a regular string:
2. We use string interpolation and add a ‘$’ sign in front of the query string: