我需要使用相同的ConnectionString
在两个地方。在我的网络项目中Insig.Api
其中包含ConnectionString
from appsettings.json
并在另一个项目类库中Insing.Infrastructure
我的数据库上下文在哪里。
Insig.Api-Startup.cs
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton(Configuration);
services.AddDbContext<InsigContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
}
Insig.基础设施-InsigContext.cs
public class InsigContext : DbContext, IDesignTimeDbContextFactory<InsigContext>
{
public InsigContext() { }
public InsigContext(DbContextOptions<InsigContext> options) : base(options) { }
public DbSet<Sample> Samples { get; set; }
public InsigContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<InsigContext>();
builder.UseSqlServer("Data Source=.\\SQLEXPRESS;Initial Catalog=InsigDB;Integrated Security=True;MultipleActiveResultSets=True");
// Here I would like to use ConnectionString instead of raw string.
return new InsigContext(builder.Options);
}
}
如你看到的ConnectionString
由于迁移(来自代码优先方法),上下文中也需要它。
编辑-下面的代码不起作用。当我试图Add-Migration Init
然后我收到一个错误:Value cannot be null. Parameter name: connectionString
public class InsigContext : DbContext
{
private readonly string _connectionString;
public InsigContext(DbContextOptions<InsigContext> options, IConfiguration configuration) : base(options)
{
_connectionString = configuration.GetSection("ConnectionStrings:DefaultConnection").Value;
}
public InsigContext() { }
public DbSet<Sample> Samples { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(_connectionString);
}
}
}