【发布时间】:2018-05-27 18:47:36
【问题描述】:
我需要在两个地方使用相同的ConnectionString。在我的 Web 项目 Insig.Api 中,其中包含来自 appsettings.json 的 ConnectionString 和另一个项目类库 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.Infrastructure - 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);
}
}
正如您所见,由于迁移(来自 Code First 方法),上下文中也需要 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);
}
}
}
【问题讨论】:
标签: c# asp.net-core