EF Core SingleOrDefaultAsync compile time return type error

async-await c# entity-framework-core linq

Question

I'm trying to write an async method that returns a single object from EF core in my repository. I have the following method:

public async Task<Administrator> GetOne(Guid guid)
{
    var admin = await _ctx.Users.SingleOrDefaultAsync(u => u.Guid == guid);
    return admin;
}

However this give the following compile time error:

Cannot convert expression type TResult to return type Administrator

If I change it to the following code (i.e. no OrDefault) I get no issues:

public async Task<Administrator> GetOne(Guid guid)
{
    var admin = await _ctx.Users.SingleAsync(u => u.Guid == guid);
    return admin;
}

What am I doing wrong?

Also a second point, is the code correct in the first place or should I just be returning the result without an await i.e.

public Task<Administrator> GetOne(Guid guid)
{
    return _ctx.Users.SingleOrDefaultAsync(u => u.Guid == guid);
}
1
1
4/19/2018 11:29:28 AM

Accepted Answer

How to solve your compilation error :

I change it to the following code (i.e. no OrDefault) I get no issues.

What am I doing wrong?

You should try the following to force the compiler to convert the return Type values and the possible default (null) type to Administrator

 ctx.Users.SingleOrDefaultAsync(u => u.Guid == guid) as Administrator;

Note :

The above code return null if there is a user with the provided id but it cannot be converted to an Administrator instance.

If you want an exception to be thrown in this case, you can use a 'classic' cast :

 (Administrator) ctx.Users.SingleOrDefaultAsync(u => u.Guid == guid);

About 'await' or 'not await'

Also a second point, is the code correct in the first place or should I just be returning the result without an await

My guess is that you want to await your code here. Ultimately, only you really know, but I can't see any abvious reason not to do so, and many reason to do await it.

If you don't await, then you get a Task out of your function, possibly not completed yet, while the rest of your calling code probably depends on the actual Administrator result.

4
4/19/2018 1:22:00 PM

Popular Answer

This method signature : public async Task<Administrator> GetOne(Guid guid) should return a Task<Administrator>.

The ctx.Users.SingleOrDefaultAsync call isn't returning a Task<Administrator>.

As for your second point: If you don't need the result just return the Task.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow