将查询和函数传递给另一个函数

时间:2015-02-19 13:08:47

标签: f#

我有一个方法可以正常工作:

 member this.GetItems = 
        let db = dbSchema.GetDataContext()             
        let getQuery = 
            query {
                for row in db.ItemsTable do
                select row
            }
        getQuery 
        |> Seq.map (fun e -> new Item(e.ItemId, e.ItemName ))
        |> Seq.toArray

它对数据库进行选择查询,将每个记录转换为对象并返回此类对象的数组。

我想将此方法拆分为两个。第一个必须更一般。它获得了将记录转换为对象的查询和功能。

这是我的代码:

member private this.ExecuteSelectQuery(query, transform_function) =
    let db = dbSchema.GetDataContext()             
    query 
    |> Seq.map transform_function
    |> Seq.toArray

member this.GetItems = 
    let db = dbSchema.GetDataContext()             

    this.ExecuteSelectQuery 
        query {
            for row in db.ItemsTable do
            select row
        } 
        (fun e -> new Item(e.ItemId, e.ItemName ))

但是我得到了错误:

  • 在此表达式中需要输入'a *('b - >'c),但有一个类型QueryBuilder
  • 此构造仅可用于方法For
  • 的情况

我该如何解决?

更新

member private this.ExecuteSelectQuery query transform_function =
    let db = dbSchema.GetDataContext()             
    query 
    |> Seq.map transform_function
    |> Seq.toArray

member this.GetItems = 
    let db = dbSchema.GetDataContext()             

    this.ExecuteSelectQuery 
        query {
            for row in db.ItemsTable do
            select row
        } 
        (fun e -> new Item(e.ItemId, e.ItemName ))

1 个答案:

答案 0 :(得分:3)

成员函数ExecuteSelectQuery期望参数为元组,因此必须使用括号。

member private this.ExecuteSelectQuery(query, transform_function) =
    query 
    |> Seq.map transform_function
    |> Seq.toArray

member this.GetItems = 
    use db = dbSchema.GetDataContext()             

    this.ExecuteSelectQuery (
        query {
            for row in db.ItemsTable do
            select row
        }, 
        (fun e -> new Item(e.ItemId, e.ItemName )))

还请考虑use关键字绑定DataContext实例以正确实现一次性模式。我已经在我的例子中完成了它。