简体   繁体   English

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

[英]How to consume this EF Core C# async method in F#?

I am using F# with Entity Framework and I can't get my head around consuming C# async methods from F#. 我正在使用带有实体框架的F#,我无法理解使用F#的C#异步方法。 Despite others SO answers related to similar issues can't really get my head around. 尽管其他与类似问题相关的SO答案无法真正解决。

Here is my attempt with the code below, initially synchronous: 这是我尝试使用下面的代码,最初是同步的:

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

And its async counterpart: 和它的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)
    }

However, when both are called in the main: 但是,当两者都被称为主要:

[<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

It cannot compile: 它无法编译:

  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'

I read: 我读:

I thought the process to consume an async C# method was: 我认为使用async C#方法的过程是:

  • Pass the C# method to |> Async.AwaitTask 将C#方法传递给|> Async.AwaitTask
  • Pass the result to let! 传递结果let!
  • Return that result 返回结果
  • Wrap everything in an async block which forms the body of an async F# function 将所有内容包装在async块中,该块构成async F#函数的主体
  • Use that newly async created F# function by passing it to |> Async.RunSynchronously 通过将新async创建的F#函数传递给|> Async.RunSynchronously

What am I missing here? 我在这里错过了什么?

The problem is that in getAirportAsync you discard flight and just return the function. 问题是在getAirportAsync您丢弃flight并返回该功能。 The fix is simple: 修复很简单:

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
    }

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

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