这里有一种方法可能适合您。
如果我在共享项目的文件夹中运行它,它将无法访问在startup.cs中指定的连接字符串。
Startup.cs
我假设在您的Startup.cs文件中,您通过访问Configuration
而不是硬编码来指定连接字符串。此外,我假设在您的Startup.cs文件的构造函数中,您正在从几个来源设置配置。换句话说,您的Startup.cs可能看起来像这样:
public class Startup
{
public IConfiguration Config { get; set; }
public Startup(IHostingEnvironment env)
{
var config = new Configuration()
.AddJsonFile("config.json")
.AddUserSecrets()
.AddEnvironmentVariables();
Config = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MyDbContext>(options =>
{
options.UseSqlServer(Config["ConnectionStrings:MyDbContext"]);
});
}
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
var db = serviceProvider.GetRequiredService<MyDbContext>();
db.Database.AsSqlServer().EnsureCreated();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
config.json
另外,我假定您将连接字符串添加到项目根目录下的config.json中(或者通过用户机密或环境变量添加)。您的config.json可能如下所示:
{
"ConnectionStrings": {
"MyDbContext": "Some-Connection-String"
}
}
如果你没有这样做过,尝试一下也许会有好处。
我从类似这样的问题中获悉,如果你在 DbContext 的 OnConfiguring 方法中指定连接字符串,它确实可以从共享项目中起作用,但我真的希望将此代码与配置分开。
DbContext
如果我的假设是正确的,那么您可以通过在 DbContext 构造函数中设置 IConfiguration 来访问连接字符串。然后,在 OnConfiguring 中访问连接字符串。可能看起来像这样:
public class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<SomeModel>().Key(e => e.Id);
base.OnModelCreating(builder);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connString = Config["ConnectionStrings:MyDbContext"];
optionsBuilder.UseSqlServer(connString);
}
public IConfiguration Config { get; set; }
public MyDbContext()
{
var config = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Config = config;
}
}
项目结构
当然,你需要在共享项目文件夹的根目录下拥有一个 config.json 文件。因此,你的项目结构可能看起来像这样:
SharedDataContext
Migrations
config.json
project.json
WebApp
config.json
project.json
Startup.cs
在上面的例子中,两个 config.json 文件都包含 DbContext
的连接字符串设置。
一些想法
如果您不喜欢重复 config.json 中的连接字符串内容,那么可以使用环境变量或用户密码来代替。