我想将连接字符串传递给我的dbcontext模型。
我正在使用Microsoft.EntityFrameworkCore.Sqlite包。
public void ConfigureServices(IServiceCollection services)
{
//Adds Entity FrameWork for SqlLite
var config = Configuration.GetConnectionString("DefaultConnection");
//How to pass the connection string, AddEntityFrameworkSqlite take no extra parameters
//services.AddEntityFrameworkSqlite().AddDbContext<ETLDataBase>(opt => opt.????)
services.AddEntityFrameworkSqlite().AddDbContext<ETLDataBase>();
services.AddMvc();
services.AddScoped<IRepository<User>, AccountRepository>();
}
我没有找到直接在我的dbcontext中访问ContentRootPath
的方法。我在appsettings.json
中对数据库的路径进行了硬编码,但即使这样,我也无法将路径传递给我的模型。
这是我的上下文模型:
public class ETLDataBase: DbContext
{
public ETLDataBase(DbContextOptions<ETLDataBase> options)
: base(options)
{}
public DbSet<Datasouce> Datasources { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// I want to get my connection string in here
//I can't access to the env.ContentRootPath
var connection = new SqliteConnection(connectionString);
optionsBuilder.UseSqlite(connection);
}
}
修改
如果我在Startup.cs
:
services.AddEntityFrameworkSqlite().AddDbContext<ETLDataBase>(options=> options.UseSqlite(Configuration["ConnectionStrings:DefaultConnection"]));
我删除了OnConfiguring
类中的ETLDataBase
函数。
我有这个错误:
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.