简体   繁体   English

F#中的异步EF查询

[英]Asynchronous EF query in F#

In C# using EF6 I can easily make asynchronous operations like this: 在使用EF6的C#中,我可以轻松地进行如下异步操作:

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? 如何使用F#异步工作流程执行相同操作?

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 (ie without permanent consumption of thread pool, like in a C# example). 我知道query工作流以及如何使用它代替LINQ,但是我不知道如何使其正确异步(即,不像C#示例那样永久占用线程池)。 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. 我正在寻找某些操作,例如headAsync (类似于C#查询中的FirstAsync )或其他可靠的解决方案。

You can use the same extension methods you use in C#. 您可以使用与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

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

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