Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous EF query in F#

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.

like image 515
ForNeVeR Avatar asked Oct 16 '25 20:10

ForNeVeR


1 Answers

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
like image 122
Jakub Lortz Avatar answered Oct 18 '25 15:10

Jakub Lortz