John H
John H

Reputation: 85

Why do I get a null reference exception when using FindAsync in Entity Framework Core?

Using .NET Core 3.1 I have a simple controller method defined as follows:

[HttpGet( "{id}" )]
public async Task<ActionResult<Animal>> Get( [FromRoute] int id )
{
    var animal = await _dbContext.Animal.FindAsync( id );
    if( animal == null ) return NotFound();
    return Ok( animal );
}

When called with a valid id, this throws a null reference exception from within FindAsync.

If I convert to a synchronous method, and use Find instead, it works as expected.

I've tried changing Task to ValueTask, or adding .AsTask() to .FindAsync(), but it makes no difference. How can I get an asynchronous call to work?

Upvotes: 2

Views: 1913

Answers (1)

Ramesh Shah
Ramesh Shah

Reputation: 321

Maybe you can try this syntax

var animal = await _dbContext.Animal.FirstOrDefaultAsync(x => x.Id == id);

Upvotes: 2

Related Questions