Parametric LINQ query

浪尽此生 提交于 2019-12-18 06:29:07

问题


This is another take on accessing dynamic objects in F# There I'm using let y = x.Where(fun x -> x.City ="London").Select("new(City,Zip)") to parametrize the query and extract the necessary items. These would correspond to columns in an SQL query, and be represented by a property of the datacontext. This is the part that I would like to pass in as a parameter.

type Northwind = ODataService<"http://services.odata.org/Northwind/Northwind.svc">
let db = Northwind.GetDataContext()
let query2 = query { for customer in db.Customers do
                     select customer}  |> Seq.toArray
let qryfun (x:Northwind.ServiceTypes.Customer) =
    query { for x in query2 do
            select (x.City,x.CompanyName,x.Country)}

Basically I would like to pass in not only x but also x.*. As I'm accessing one database that is fixed, I can factor out x. However I now have 40 small functions extracting the different columns. Is it possible to factor it out to one function and pass the property as an argument? So sometimes I extractx.City but other times x.Country. I have tried using quotations however cannot splice it properly and maybe that is not the right approach.


回答1:


Regarding quotation splicing, this works for me:

open System.Linq

type record = { x:int; y:string }

let mkQuery q =
    query {
        for x in [{x=1;y="test"}].AsQueryable() do
        select ((%q) x)
    }

mkQuery <@ fun r -> r.x, r.y @>
|> Seq.iter (printfn "%A")


来源:https://stackoverflow.com/questions/36540777/parametric-linq-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!