An error occurred while accessing the Microsoft.Extensions.Hosting services when do first migrations

后端 未结 1 342
天涯浪人
天涯浪人 2021-01-17 18:32

I dont understand what wrong. i try make simple simple crud in .net core mvc with a very simple model wich have few fields

this is my models

    publ         


        
相关标签:
1条回答
  • 2021-01-17 19:15

    EF calls CreateWebHostBuilder or BuildWebHost without running Main. So Iconfiguration is null.

    Create new class which inherited from IDesignTimeDbContextFactory .

    public class EmployeeContext : DbContext
    {
    //Dbcontext implementation
    }
    
    public class EmployeeFactory : IDesignTimeDbContextFactory<EmployeeContext>
    {
        public EmployeeContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<EmployeeContext>();
            optionsBuilder.UseSqlServer("your connection string");
    
            return new EmployeeContext(optionsBuilder.Options);
        }
    }
    

    You are using a new .net core EF which uses IHostBuilder.(in an older version like yours the provider is IWebHostBuilder). The tools first try to obtain the service provider by invoking the Program.CreateHostBuilder(), calling Build(), then accessing the Services property.

    EF needs to build the model and use the DbContext without starting the application. When EF invokes methods, your config services are still null that's why you get an error.

    Make sure you have installed the package

    Microsoft.EntityFrameworkCore.Tools

    0 讨论(0)
提交回复
热议问题