Have been on this for hours now and even after searching other solutions online, I'm still not able to understand/resolve this error!
I have a blazor application where I'd like to load data, via a DI service, when the index page is initialized. Below is a summarized version of my code:
Startup.cs
...
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbContext")));
...
services.AddTransient<IMyDbService, MyDbService>();
...
DbContext.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;
}
}
and finally calling within
Index.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();
}
}
I've walked through the code and the exception is thrown on the LINQ query
var result = await MyDbContext.Items
.Include(i => i.Log)
.ToListAsync();
I've tried:
- reading blazor documentation
- removing the .Include(...) - same error
- added a debug code that does a synchronous call within the same method -
var t = MyDbContext.Items.Include(i => i.Log).ToList();
. This works - going to sleep thinking on this problem, and waking up the next day - same error.
I must be overlooking something ?
EDIT With thanks to Henk Holterman, realized that the exception stack message shows a .Where() being called... which, by following the code, is being called within the index component view. Have also updated index.razor.cs with more accurate code.
<div class="row text-center">
<div class="col">
...
<h4>@Dashboard.Items.Where(x => x.Status == ItemStatus.New).Count()</h4>
...
</div>
</div>
</div>