这是一种可能适合您的方法。
如果我在共享项目的文件夹中运行它,它无法访问startup.cs中指定的连接字符串。
启动.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!");
});
}
}
配置.json
此外,我假设您将连接字符串添加到项目根目录中的 config.json (或者通过用户机密或环境变量添加它。)您的 config.json 可能如下所示:
{
"ConnectionStrings": {
"MyDbContext": "Some-Connection-String"
}
}
如果您不这样做,那么可能值得尝试。
我从这样的问题中了解到,如果您在 DbContext 的 OnConfiguring 方法中指定连接字符串,它确实可以在共享项目中工作,但我真的希望将此代码与配置分开。
数据库上下文
如果我上面的假设是正确的,那么您可以访问连接字符串DbContext
通过使用与您在中使用的相同的模式Startup
班级。也就是说,在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 连接字符串内容,那么您可以使用环境变量或用户机密。