Home > database >  Getting "'Cannot access a disposed object" error when trying to update database on st
Getting "'Cannot access a disposed object" error when trying to update database on st

Time:10-29

We have a Web API Core application that use the EF Core with the SQL Server in a backend. I am trying to update one of the database tables whenever the Web API service starts (in a Startup.cs Configure method)

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SomeDBContext dataContext, ILoggerFactory loggerFactory)
{ 
    .......................
    // Automatically perform database migration
    dataContext.Database.Migrate();

    PopulateSomeTable(dataContext);
}

private async void PopulateSomeTable(SomeDBContext context)
{
    var someTables = context.SomeTables;
    if (someTables != null && (await someTables .CountAsync()) == 0)
    {
         someTables .Add(new Entities.SomeTable
         {
             someProperty1= 20,
             someProperty2 = "Something",
             someProperty3 = DateTimeOffset.Now,
         });
         await context.SaveChangesAsync();
    }
}

However, when I try to access the context I get this error

Cannot access a disposed object. A common cause of this error is disposing a context 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, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context

How can I fix it?

Thank you in advance

CodePudding user response:

You need to replace private async void PopulateSomeTable(SomeDBContext context) to private async Task PopulateSomeTable(SomeDBContext context). Replace async void to async task. Check this link for more info.

CodePudding user response:

remove all your code from startup, it is not the best place to make db migration, and add only this code

 public static void Configure(IApplicationBuilder app, IWebHostEnvironment env, MyDbContext context)
    {
        if (env.IsDevelopment())
        {
            context.Database.EnsureCreated();
         }
    }

add this code to ConfigureServices of startup

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
    .AddNewtonsoftJson(options =>
           options.SerializerSettings.ContractResolver =
              new CamelCasePropertyNamesContractResolver());

services.AddDbContext<SomeDBContext (options => 
options.UseSqlServer(Configuration.GetConnectionString("CategoryDbConnection")));

to populate data add code like this OnModelCreating of SomeDBContext

modelBuilder.Entity<SomeTable>().HasData(
    new SomeTable{ ....
                 });

to migrate classes to database tables follow this link https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=vs

  • Related