首页 > 解决方案 > 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();

错误截图

我试过了:

我一定是忽略了什么?

编辑 感谢 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>

标签: c#asynchronousblazorblazor-server-side.net-5

解决方案


啊找到了解决办法!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>

推荐阅读