In the previous entry, we saw that we could execute arbitrary queries with Entity Framework Core 2.0, in addition, we saw that we could pass parameters to said queries using an array of SqlParameters. In this post we will see how to send parameters to arbitrary queries using String Interpolation.
We recall that String Interpolation is an added functionality in C# 6 which consists in facilitating the concatenation of strings with variables. Let’s see an example of String Interpolation:
string name = "Felipe"; int age = 895; string template = $"My name is {name} and I am {age} years old.";
What this code does is to create the string “My name is Felipe and I am 895 years old.”. As you can see, string interpolation allows us to insert values within a string with a quite comfortable syntax.
Going back to the Entity Framework Core, the idea of using String Interpolation is to be able to send parameters to our arbitrary queries with String Interpolation and Entity Framework will automatically convert those values of the variables that we insert into our query into parameters. Let’s see an example:
var Id = 3; using (var context = new ApplicationDbContext ()) { var student = context.Students. FromSql($"SELECT * from Students where Id = {Id}").FirstOrDefault(); }
When we execute the previous query, the Id value will be converted into an SQL parameter, which automatically protects us from an SQL injection attack.