[英]EF Core - FirstOrDefaultAsync throws Null Reference Exception
I am trying to test ASP.NET Core Web API controllers using XUnit. 我正在尝试使用XUnit测试ASP.NET Core Web API控制器。 I am using the DBContext directly in the controller. 我直接在控制器中使用DBContext。 In production, I am using SqlServer and for testing, I am using InMemory provider. 在生产中,我正在使用SqlServer,并且为了进行测试,我正在使用InMemory提供程序。 When I am testing some code which is using the EF Core FirstOrDefaultAsync
method, the application is throwing null reference exception. 当我测试一些使用EF Core FirstOrDefaultAsync
方法的代码时,应用程序将FirstOrDefaultAsync
空引用异常。 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. 根据我的理解,它应该返回NULL,不应引发异常。
I tried something like where(x => x.Id = id).FirstOrDefaultAsync()
, it is also throwing the same null reference exception. 我尝试了诸如where(x => x.Id = id).FirstOrDefaultAsync()
,它也抛出了相同的null引用异常。
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. dbcontext和users属性都是值,这些值不为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. 目前,我能够使用最新的EF Core 3.0 Preview 7来重现它。它在内存提供程序中发生FirstOrDefault[Async]
和SingleOrDefault[Async]
方法。 Does not happen with First[Async]
or Single[Async]
. First[Async]
或Single[Async]
不会发生。
Anyway, the main problem here is that you are using a preview (beta) software, which is expected to have issues. 无论如何,这里的主要问题是您使用的是预览 (beta)软件,该软件可能会出现问题。
Simply switch to the latest stable EF Core 2 version and wait for 3.0 release before trying to use it in production code. 只需切换到最新的稳定EF Core 2版本,并等待3.0发布,然后再尝试在生产代码中使用它即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.