Asynchronous EF query in F#

谁说我不能喝 提交于 2020-01-15 08:44:10

问题


In C# using EF6 I can easily make asynchronous operations like this:

using (var context = new MyDbContext()) {
    var item = await context.SomeEntities.Where(e => e.Id == 1).FirstAsync();
    DoSomething(item);
}

How could I do the same with F# async workflow?

I am aware of query workflow and how to use it instead of LINQ, but I have no idea how to make it properly async (i.e. without permanent consumption of thread pool, like in a C# example). Here's what I got so far (it is synchronous):

use context = MyDbContext()
let item = query {
    for e in context.SomeEntities
    where (e.Id = 1)
    head
}
DoSomething item

I am looking for some operation like headAsync (analogous to FirstAsync in C# query) or other reliable solution.


回答1:


You can use the same extension methods you use in C#.

open System.Data.Entity

let asyncQuery = async {
    return! 
        query { 
        for e in context.SomeEntities do
        where (e.Id = 1)
        select e}
        |> QueryableExtensions.FirstAsync
        |> Async.AwaitTask
}

let result = Async.RunSynchronously asyncQuery


来源:https://stackoverflow.com/questions/32806981/asynchronous-ef-query-in-f

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