简体   繁体   中英

F# constructor with <“string”, str>

In this article it shows how to use the SqlCommandProvider type. The sample code has this:

use cmd = new SqlCommandProvider<"
    SELECT TOP(@topN) FirstName, LastName, SalesYTD 
    FROM Sales.vSalesPerson
    WHERE CountryRegionName = @regionName AND SalesYTD > @salesMoreThan 
    ORDER BY SalesYTD
    " , connectionString>(connectionString)

what does the <... ,...> before the type constructor name mean and why the the first parameter have to be a string literal? It looks like a generic but it's taking variables not types. The constructor seems to be taking in a connection string already in the <> section.

The angle brackets are the configuration for a type. In your example, you are defining a type and creating an instance at the same type. It's clearer when the steps are separated.

Define a type.

type SalesPersonQuery = SqlCommandProvider<query, connectionString>

But to actually have an instance of the type you have to create it:

let command = new SalesPersonQuery()

Now you can use the command.Execute() rather then SalesPersonQuery.Execute() .

The reason there is a constructor is because later on (at run-time) you can change the connection string to a different then the one provided in the definition, so for instance:

let command = new SalesPersonQuery(differentConnectionString)

You can find that in the documentation in configuration section:

Connection string can be overridden at run-time via constructor optional parameter

First parameter can be a path to a SQL script or a SQL query. I suppose that's the reason it's a string: how else would you like to define a SQL query?

Again, from the documentation:

Command text (sql script) can be either literal or path to *.sql file

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