没有数据库提供商.Net Core Angular应用

时间:2019-05-28 18:23:59

标签: .net sql-server asp.net-core

我正在尝试使用.NET Core 2.2和Angular构建数据库,并且遇到了此错误:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

我的ApplicationDbContext类中有一个默认构造函数。

public class ApplicationDbContext : DbContext
{
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base()
        {
        }
}

我的程序CS对我来说还不错:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(SetUpConfiguration)
                .UseStartup<Startup>();

        private static void SetUpConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder builder)
        {
            builder.Sources.Clear();
            builder.AddJsonFile("appsettings.json", false, true)
                    .AddEnvironmentVariables();
        }
    }

我的创业公司注册了数据库:

private readonly IConfiguration _config;
        public Startup(IConfiguration config)
        {
            _config = config;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<ApplicationDbContext>(cfg => {
                cfg.UseSqlServer(_config.GetConnectionString("LevanaConnectionString"));
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

2 个答案:

答案 0 :(得分:0)

您没有将选项传递给基本构造函数:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base(opts) // <-- this
    {
    }
}

答案 1 :(得分:0)

我们在第一条消息中可以看到: “如果使用AddDbContext,还请确保您的DbContext类型在其构造函数中接受DbContextOptions对象,并将其传递给DbContext的基本构造函数。”

您正在“ ConfigureServices”类中使用“ AddDbContext”,但不要在“ ApplicationDbContext”中为“ DbContext”的基本构造函数传递“ DbContextOptions”。

您可以尝试以下方法:

public class ApplicationDbContext : DbContext
{
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base(opts)
        {
        }
}