mehrandvd mehrandvd -3 years ago 109
C# Question

String interpolation in raw SQL methods, How is it possible?

I've just checked the new futures in Entity Framework Core 2.0. There is a really nice feature in it called "String interpolation in raw SQL methods" which is described here.

It says that this code:

var city = "Redmond";

using (var context = CreateContext())
FROM Customers
WHERE City = {city}");

creates this query:

FROM Customers
WHERE City = @p0

It is really strange to me! How
method is written as it has just and input of type string.

How does it understand it is an interpolated string, and then create a parameter
query for it? How can I write a method like
aware of how its string parameters are created?

Answer Source

The way it woks is FromSql( accepts a FormattableString.

When you use $"..." that returns a FormatableString, that class allows you to inspect the passed in string and see all of the { } blocks inside of and the objects they represent. This allows the framework to replace those { } blocks with a placeholder parameter @p0 then create a new parameter using something similar to new SqlParameter("@p0", formatableString.GetArgument(0))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download