Bind Collections using IDbContextFactory

I am about to create a blazor application with ef core. I read the Microsoft recommentation about how to Setup EF Core DbContextFactory

Until now i used in my Razor-Components bindindings to the DbSet like

<select @bind-value="dbContext.People" />

since I read the Article I'm a little confused of how to used it now, because they use the dbcontext inside of a using-Statement.

because of the using statement i cant directly bind a dbset anymore???

@inject IDbContextFactory<DatabaseContext> DbFactory

<select @bind-value="dbContext.People" />

@code
{
    DatabaseContext dbContext;

    protected override Task OnInitializedAsync()
    {
        using var dbContext = DbFactory.CreateDbContext();
    }
}

Whats your suggestion for that?

If i use

<input @bind-value="People" />

@code
{
    ICollection<Person> People;

    protected override Task OnInitializedAsync()
    {
        using var dbContext = DbFactory.CreateDbContext();
        People = dbContext.People;
    }
}

nothing will be displayed. The Debugger tells me:

Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'DatabaseContext'.

1 answer

  • answered 2021-01-19 09:35 Henk Holterman

    //DatabaseContext dbContext;
    ICollection<Person> persons = null;
    
    protected override async Task OnInitializedAsync()
    {
        using var dbContext = DbFactory.CreateDbContext();
        persons = await dbContext.Person.ToArrayAsync();
    }
    

    and make sure to use @if (persons != null) { ... } in the markup.