简体   繁体   English

fsharp数据SqlClient的命名参数

[英]Named Parameters with fsharp data SqlClient

I am having trouble getting this code to compile when loading the T-Sql from an external file. 从外部文件加载T-Sql时,我无法获取此代码进行编译。 The code works when the T-Sql is inserted directly in F# as: 将T-Sql直接插入F#中时,代码可以正常工作:

 type GetRecentMedia =
        SqlCommandProvider<"DECLARE @MedId NVARCHAR(128);
                            DECLARE @TopN INT;

                            select Top(@TopN) * from media.mediaInfo
                            where MediaId = @MedId",
                            Admin.connectionString, ConfigFile = "Web.config">

But I get this error when trying to load T-Sql from a sql file: 但是尝试从sql文件加载T-Sql时出现此错误:

Execute takes 0 arguments but here is given 2. Execute接受0个参数,但此处给出2。

T-Sql: T-SQL:

DECLARE @MedId NVARCHAR(128);
DECLARE @TopN INT;

select Top(@TopN) * from media.mediaInfo
where MediaId = @MedId

F#: F#:

module internal FeedRecentMedia =

    type GetRecentMedia =
        SqlCommandProvider<"Social\InstagramFeed_Select_GetRecentMedia.sql",
                            Admin.connectionString, ConfigFile = "Web.config">
module MediaTool =

    // get current media
    let rM = new FeedRecentMedia.GetRecentMedia()
    let curMedia = rM.Execute(MedId = "Id", TopN = 1) |> Seq.head

I tested the t-sql in management studio and it works there. 我在Management Studio中测试了T-SQL,它在那里工作。 I only get the above mentioned error. 我只会遇到上述错误。 What am I missing here? 我在这里想念什么?

This is a documented limitation of the SqlClient type provider. 这是SqlClient类型提供程序的已记录限制。 The parameters you pass from F# code to T-SQL must be 从F#代码传递到T-SQL的参数必须为

  • undeclared (which can be a problem if the type is ambiguous, eg for numeric types) 未声明(如果类型不明确,例如对于数字类型,可能会出现问题)
  • used only once 仅使用一次

Fortunately, the same workaround provided in the docs solves both problems: you declare a variable using the outer variable as parameter. 幸运的是,文档中提供的相同解决方法可以解决这两个问题:您可以使用外部变量作为参数来声明变量。 This also lets you explicitly annotate the type: 这还使您可以显式注释类型:

type FizzOrBuzz = SqlCommandProvider<"
    DECLARE @x AS INT = @xVal
    SELECT 
        CASE 
            WHEN @x % 3 = 0 AND @x % 5 = 0 THEN 'FizzBuzz' 
            WHEN @x % 3 = 0 THEN 'Fizz' 
            WHEN @x % 5 = 0 THEN 'Buzz' 
            ELSE CONCAT(@x, '') --use concat to avoid nullable column
        END", connectionString>

let fizzOrBuzz = new FizzOrBuzz()
printfn "Answer on interview:\n%A" [ for i = 1 to 100 do yield! fizzOrBuzz.Execute(i) ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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