c# - ArgumentNullException:值不能为空。(参数'source')调用 ToListAsync() 时
问题描述
已经研究了几个小时,即使在网上搜索了其他解决方案后,我仍然无法理解/解决这个错误!
我有一个 Blazor 应用程序,我想在初始化索引页面时通过 DI 服务加载数据。以下是我的代码的摘要版本:
启动.cs
...
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbContext")));
...
services.AddTransient<IMyDbService, MyDbService>();
...
数据库上下文.cs
public class MyDbContext : DbContext
{
public MyDbContext() { }
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
public virtual DbSet<Item> Items { get; set; }
}
IMyDbService.cs
public class MyDbService : IMyDbService
{
private MyDbContext MyDbContext { get; set; }
public MyDbService (MyDbContext myDbContext)
{
MyDbContext = myDbContext;
}
public async Task<IEnumerable<Item>> Get()
{
var result = await MyDbContext.Items
.Include(i => i.Log)
.ToListAsync();
return result;
}
}
最后在里面打电话
索引.razor.cs
public partial class Index
{
[Inject]
protected IMyDbService MyDbService { get; set; }
public Dashboard Dashboard { get; set; } = new Dashboard();
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
Dashboard.Items = await MyDbService.Get();
}
}
我已经浏览了代码,并且在 LINQ 查询中引发了异常
var result = await MyDbContext.Items
.Include(i => i.Log)
.ToListAsync();
我试过了:
- 阅读 blazor 文档
- 删除 .Include(...) - 同样的错误
- 添加了在同一方法中执行同步调用的调试代码 -
var t = MyDbContext.Items.Include(i => i.Log).ToList();
. 这有效 - 想着这个问题睡觉,第二天醒来-同样的错误。
我一定是忽略了什么?
编辑 感谢 Henk Holterman,意识到异常堆栈消息显示 .Where() 被调用...通过遵循代码,它正在索引组件视图中被调用。还使用更准确的代码更新了 index.razor.cs。
<div class="row text-center">
<div class="col">
...
<h4>@Dashboard.Items.Where(x => x.Status == ItemStatus.New).Count()</h4>
...
</div>
</div>
</div>
解决方案
啊找到了解决办法!index.razor 中的以下部分触发了异常。第一次加载索引组件时,似乎Dashboard.Items
仍然是null
.
所以解决方法是更换
<h4>@Dashboard.Items.Where(x => x.Status == ItemStatus.New).Count()</h4>
和
<h4>@Dashboard.Items?.Where(x => x.Status == ItemStatus.New).Count()</h4>
推荐阅读
- angular - 如何在角度 7 中显示从 .ts 类到 .html 的日期格式?
- json - 验证 JSON 时出现异常“EOF”
- javascript - 从函数返回多个值并在承诺中分配返回值时遇到问题
- ruby-on-rails - HTTParty 不打印响应
- python-3.x - 无法从这些图像中提取文本
- spring - Spring Boot 2 HandlerInterceptor 在身份验证之前未调用
- python - 使用 Python 的 POST 请求 API - 状态码 500
- scala - Spark-elasticsearch 使用 spark 从 elasticsearch 中获取过滤后的记录
- c# - 使用 EF Core 和 Azure Functions 更新数据库时无法访问已释放的对象
- z3 - Z3 使用量词的相关性传播