Ben Thomson
Ben Thomson

Reputation: 1123

EF Core SingleOrDefaultAsync compile time return type error

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);
}

Upvotes: 2

Views: 1214

Answers (2)

Pac0
Pac0

Reputation: 23129

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.

Upvotes: 4

Sievajet
Sievajet

Reputation: 3513

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.

Upvotes: 0

Related Questions