.NET实体框架核心数据库连接失败

时间:2019-11-18 16:58:09

标签: c# entity-framework-core

我有一个使用EFC连接数据库的简单API应用程序。

在我的localhost测试中一切正常

appsettings.json中:

"ConnectionStrings": {
    "DevConnection": "Server=(local);Database=CentoWebDB;Trusted_Connection=True;MultipleActiveResultSets=True;"
}

在Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options =>
            {// avoid naming convention;
                var resolver = options.SerializerSettings.ContractResolver;
                if (resolver != null)
                    (resolver as DefaultContractResolver).NamingStrategy = null;
            });

        services.AddDbContext<CentoWebDBContext>(
            options => 
                options.UseSqlServer(
                    Configuration.GetConnectionString("DevConnection"),
                    sqlServerOptions => sqlServerOptions.CommandTimeout(120)
                )   // set the timeout
        );

        services.AddCors();
    }

但是,当我试图通过如下添加UseKestrel和UseUrls使api应用程序可从远程访问时,它无法连接到数据库。

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .UseUrls("http://10.10.10.10:5000", "http://localhost:5000")
            .UseStartup<Startup>();
}

错误消息:

  

失败:Microsoft.AspNetCore.Server.Kestrel [13]
  连接ID“ 0HLRC8TEROPG9”,请求ID“ 0HLRC8TEROPG9:00000001”:应用程序引发了未处理的异常。
  System.ArgumentNullException:值不能为null。
  参数名称:connectionString

     

在Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(字符串值,字符串parameterName)
  在Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder,String connectionString,Action 1 sqlServerOptionsAction)
at TSPfizer.CentoMiner.Web.Startup.<ConfigureServices>b__4_1(DbContextOptionsBuilder options) in C:\Users\shangl02\source\repos\TSolution\CentoMinerWebAPI\Startup.cs:line 43
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass1_0
2.b__0(IServiceProvider p,DbContextOptionsBuilder b)

似乎连接字符串为空。不明白哪里出了问题。我在那里错过了什么吗?

0 个答案:

没有答案