gpt4 book ai didi

c# - 不使用本地数据库的 Docker "LocalDB is not supported"中的 Net Core 应用程序

转载 作者:行者123 更新时间:2023-11-30 17:25:42 31 4
gpt4 key购买 nike

我有一个运行 SQL 数据库的 Net.Core 应用程序。连接字符串在环境变量中。

在本地 IIS 上,应用程序运行良好。

与 Docker-Container 相同的应用程序出现以下错误

fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HLPO85V83VNO", Request id "0HLPO85V83VNO:00000001": An unhandled exception was thrown by the application. System.PlatformNotSupportedException: LocalDB is not supported on this platform.
at System.Data.SqlClient.SNI.LocalDB.GetLocalDBConnectionString(String localDbInstance)
at System.Data.SqlClient.SNI.SNIProxy.GetLocalDBDataSource(String fullServerName, Boolean& error)

Docker 的环境变量:"DB_CONNECTION": "Server=hc-XXX; Database=IB33DB-Core_XXX; User Id=sa;Password=XXX"

这是网络中的设置

Network info

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ib.api_core.Data;
using Microsoft.EntityFrameworkCore;
using ib.api_core.Models;

namespace ib.api_core
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

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)
.AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

string dbConnection = Environment.GetEnvironmentVariable("DB_CONNECTION");
Console.WriteLine("Env var DB Connection: "+dbConnection);

//Verweis auf den Datenbank Kontext
services.AddDbContext<ibContext>(options =>
options.UseSqlServer(dbConnection));

//Verweis auf den Datenbank Kontext
// services.AddDbContext<ibContext>(options =>
// options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}


//1. Alle Anfragen in der Konsole loggen
app.UseMiddleware<RequestResponseLoggingMiddleware>();
//2. Prüfe Login und Berechtigung der Anfrage
app.UseMiddleware<AuthenticationMiddleware>();

app.UseHttpsRedirection();
app.UseMvc();
}
}
}

ibContext.cs

using System;
using Microsoft.EntityFrameworkCore;
namespace ib.api_core.Models
{
public partial class ibContext : DbContext
{

public ibContext()
{
}

public ibContext(DbContextOptions<ibContext> options)
: base(options)
{
}

public static ibContext GetContext()
{
var optionsBuilder = new DbContextOptionsBuilder<ibContext>();
optionsBuilder.UseSqlServer(Environment.GetEnvironmentVariable("DB_CONNECTION"));
return new ibContext(optionsBuilder.Options);
}

[...]


protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(Environment.GetEnvironmentVariable("DB_CONNECTION"));
}
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
....

最佳答案

错误消息意味着在某些时候,您的代码尝试使用为 LocalDB 配置的连接字符串访问数据库。我怀疑在您的 appsettings.json 中,有一个使用 LocalDB 的连接字符串,该字符串有时会被使用。

从代码示例中我无法找出原因。也许某些代码绕过环境变量并从配置文件中读取连接字符串,或者容器运行旧版本的代码。


但是,在基于此 sample 的项目中我能够覆盖容器中的连接字符串:

以下代码使用.NET Core configuration获取连接字符串。这种方法的优点是您可以通过多种方式提供连接字符串,并在运行容器时覆盖它。

上下文

示例中使用的上下文很简单:

public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }

public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}

设置

startup.cs 中,使用 .NET Core 配置注册上下文并检索连接字符串:

var connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<BloggingContext>
(options => options.UseSqlServer(connection));

开发配置

为了开发,使用在 appsettings.json 中配置的 LocalDB:

{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;ConnectRetryCount=0"
}
}

覆盖容器的连接字符串

运行容器时,名为 ConnectionStrings:DefaultConnection 的环境变量会覆盖 appsettings 文件中的连接字符串。

为了调试,我在 launchsettings.json 中插入了一个环境变量:

...
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"environmentVariables": {
"ASPNETCORE_URLS": "https://+:443;http://+:80",
"ASPNETCORE_HTTPS_PORT": "44330",
"ConnectionStrings:DefaultConnection": "Data Source=MY_IP\\MY_INSTANCE;Initial Catalog=TestDb;User Id=MY_USER;Password=MY_PWD"
},
"httpPort": 10000,
"useSSL": true,
"sslPort": 44330
}
...

在 IIS Express 中运行时,使用来自 appsettings.json 的连接字符串,在容器中运行时,主机上的 SQL Server 实例按照环境变量中的配置进行访问。 p>

关于c# - 不使用本地数据库的 Docker "LocalDB is not supported"中的 Net Core 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57923792/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com