我将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#方法的过程是:
|> Async.AwaitTask
let!
async
F#函数主体中的async
块中async
将F#函数传递给|> Async.RunSynchronously
我在这里想念什么?
答案 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
}