如何在F#中使用此EF Core C#异步方法?

时间:2019-04-16 07:39:46

标签: c# asynchronous f# async-await

我将F#与Entity Framework结合使用,我无法理解使用F#中的C#异步方法。尽管有其他答案,但与类似问题相关的答案仍无法真正引起我的注意。

这是我尝试下面的代码,最初是同步的:

let getAirport (id: Guid) =
    use context = new MyContext()
    context.Flights.Find id
    |> (fun x -> if box x = null then None else Some x)

及其async对应对象:

let getAirportAsync (id: Guid) =
    async {
        use context = new MyContext()
        let! flight = context.Airports.FindAsync id |> Async.AwaitTask
        return (fun x -> if box x = null then None else Some x)
    }

但是,当两者在主体中同时调用时:

[<EntryPoint>]
let main argv =
    let myGuid = Guid.NewGuid()
    let airport = {
        Id = myGuid
        Name = "Michelle"
        X = 42.0
        Y = 42.0
    }
    AirportRepository.addAirport airport
    let thisAirport = AirportRepository.getAirport myGuid
    let thisAirportToo = AirportRepository.getAirportAsync myGuid |> Async.RunSynchronously
    assert (thisAirport = Some airport)
    assert (thisAirportToo = Some airport)
    0

它不能编译:

  Program.fs(61, 13): [FS0001] The type '('a -> 'a option)' does not support the 'equality' constraint because it is a function type
  Program.fs(61, 30): [FS0001] This expression was expected to have type    ''a -> 'a option'    but here has type    ''b option'

我读到

我认为使用async C#方法的过程是:

  • 将C#方法传递给|> Async.AwaitTask
  • 将结果传递到let!
  • 返回结果
  • 将所有内容包装在async F#函数主体中的async块中
  • 使用新创建的async将F#函数传递给|> Async.RunSynchronously

我在这里想念什么?

1 个答案:

答案 0 :(得分:3)

问题在于,在getAirportAsync中,您丢弃了flight而只返回了该函数。解决方法很简单:

let getAirportAsync (id: Guid) =
    async {
        use context = new MyContext()
        let! flight = context.Airports.FindAsync id |> Async.AwaitTask
        return if box flight = null then None else Some flight
    }