8

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())
{
    context.Customers.FromSql($@"
        SELECT *
        FROM Customers
        WHERE City = {city}");
}

creates this query:

SELECT *
FROM Customers
WHERE City = @p0

It is really strange to me! How FromSql 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 @p0 query for it? How can I write a method like FromSql aware of how its string parameters are created?

7
  • I'm following C# features 6 and 7, but I haven't heard such feature before!? How can I write a method like FromSQL? Commented Aug 15, 2017 at 18:05
  • @mehrandvd while I do not claim to know how they do it, what is happening is that within the method they extract the place holders found within the string create parameters with them and replace the place holders in the string with the parameter names. Commented Aug 15, 2017 at 18:11
  • @Vanna my question is about FromSql. You mean that it replaces all values with parameters? For example if I had AND IsActive = 1, it would create another @p2, despite is is not being interpolated? Commented Aug 15, 2017 at 18:12
  • 2
    Presumably, FromSql accepts a FormattableString, not a string. Commented Aug 15, 2017 at 18:13
  • 1
    Another similar question about string interpolation stackoverflow.com/questions/29068194/… Commented Aug 15, 2017 at 18:17

1 Answer 1

9

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))

Sign up to request clarification or add additional context in comments.

4 Comments

Looks like FromSql also has an overload that directly accepts FormattableStrring.
just saw that, updating
this conflicts with Oracle Text escaping via {}. How to disable this in EF?
Use double {{ and }} to escape the { }.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.