简体   繁体   中英

Interpolated strings in F#

I am trying to use the Entity Framework Core interpolated SQL query function in F# which requires a FormattableString . However to my surprise it doesn't function as I cannot find a way to convert a regular F# string to that type. I figured just doing what you do in C# would work but it doesn't. Here is the code I currently have:

let fromDbUser (u : Entity.User) = 
    {
        name = u.Name
        age = u.Age
        phone = u.Phone
    }

let mname = "Foo" 

let ctx = new Entity.DatabaseContext()
ctx.User.FromSqlInterpolated($"Select * FROM User Where name = {mname};") 
|> Seq.map(fromDbUser)
|> printfn "%A"

Running that block of code yields a compile error:

This token is reserved for future use

I have been trying to google around but I was unable to find any way to get this to work, any help would be most appreciated!

When this was asked, F# didn't have string interpolation.

Today though, there is an RFC for it that is merged in in F# 5.0 allowing string interpolation in F#.


The error was because the $ symbol is reserved (for 6 years+ as of writing), and will probably be used for string interpolation when it is added.

As Dave pointed out, interpolation isn't implemented yet. But for methods that absolutely require an FormattableString or an IFormattable , you can use FormattableStringFactory.Create

let query (sql: FormattableString)  = 
    printfn "%s" (sql.ToString(null, null))

let mname = "Foo"         
let fstr = FormattableStringFactory.Create("Select * FROM User Where name = {0};", mname)

query fstr

It's available from F# 5.0.

> let mname = "Foo" ;;
val mname : string = "Foo"

> let str = $"Select * FROM User Where name = {mname};" ;;
val str : string = "Select * FROM User Where name = Foo;"

Check this out. https://docs.microsoft.com/en-us/dotnet/fsharp/whats-new/fsharp-50#string-interpolation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM