C
C#2y ago
Esa

❔ EntityFramework async where possible?

So I want to make sure I don't do something stupid here. I'm trying to convert my DbContext-calls to async calls where possible. I see EF provides .FirstOrDefaultAsync() which works nicely for the Get calls I have. However I need to do stuff like join and where which I see has no async overload. I started doing
Task.Run(async () => await myDbContext.MyDbSet.Join() // etc
Task.Run(async () => await myDbContext.MyDbSet.Join() // etc
but that feels wrong. How do I make this particular call async without doing something explosively stupid?
13 Replies
cumslvt13
cumslvt132y ago
Can you show the Join method signature? I don't think that Join triggers query at all There are multiple method that trigger the query execution (they have both sync and async variants) and rest of them is are sync since they do not execute query
Esa
EsaOP2y ago
This is the xml docs I get for the method:
cumslvt13
cumslvt132y ago
so how you await it? in you example? When it just returns a IQueryable
Esa
EsaOP2y ago
This makes sense:) So my method is Join().Where().Select().ToList()
cumslvt13
cumslvt132y ago
Yes The code you've shown is not valid at all
Esa
EsaOP2y ago
Yea so this is the part I don't get, the nature of EF is data transfer between my app and a data source, so there has to be some IO involved. Why can't I find any async overload to obtain the info my method provides? What is not valid at all?
cumslvt13
cumslvt132y ago
**await** myDbContext.MyDbSet.Join() await, since Join doesn't return a Task so nothing to be awaited ToListAsync() to be precise
Esa
EsaOP2y ago
Right, which is why I considered wrapping it in a Task Oh.. There is an overload for that, I didn't check. That makes sense
cumslvt13
cumslvt132y ago
First, Single, Last, Any, Average, Max, Count, Sum, etc - all of this launches a db query and their async variants ofc too
Esa
EsaOP2y ago
okay, that makes sense. I've been using a nuget library for most of my collections, so I don't really use List etc in my application. I didn't think to check if ToList() executes a query, but it makes sense that it does. I'll remember this, thanks 🙂
cumslvt13
cumslvt132y ago
If it returns something otherwise than IQueryable - it executes the query
Esa
EsaOP2y ago
That's useful to know, cheers 🙂
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server