简体   繁体   中英

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.

空引用异常

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.

立即窗口

Please help.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM