Anuraj
Anuraj

Reputation: 19598

EF Core - FirstOrDefaultAsync throws Null Reference Exception

I am trying to test ASP.NET Core Web API controllers using XUnit. I am using the DBContext directly in the controller. In production, I am using SqlServer and for testing, I am using InMemory provider. When I am testing some code which is using the EF Core FirstOrDefaultAsync method, the application is throwing null reference exception. The value I am looking for doesn't exist in the DB. As per my understanding, it should return NULL, it should not throw an exception.

I tried something like where(x => x.Id = id).FirstOrDefaultAsync(), it is also throwing the same null reference exception.

Null Reference exception

When I tried something like

var exist = await list.AnyAsync(x => x.Id == id);
if(!exist)
{
return NotFound();
}
var user = await list.FirstAsync(x => x.Id == id);
return user;

It works. Both dbcontext and users property are got values, those are not null.

Immediate Window

Please help.

Upvotes: 1

Views: 4461

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205539

The exception is not caused by your code. I was able to reproduce it with the latest at this time EF Core 3.0 Preview 7. It happens with the in-memory provider - FirstOrDefault[Async] and SingleOrDefault[Async] methods. Does not happen with First[Async] or Single[Async].

Anyway, the main problem here is that you are using a preview (beta) software, which is expected to have issues.

Simply switch to the latest stable EF Core 2 version and wait for 3.0 release before trying to use it in production code.

Upvotes: 5

Related Questions