Передать строку подключения в dbcontext для Sqlite

#c# #entity-framework #sqlite #asp.net-core #asp.net-core-mvc

#c# #entity-framework #sqlite #asp.net-ядро #asp.net-core-mvc

Вопрос:

Я хотел бы передать строку подключения в мою модель 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>();
}
  

Я не нашел способа получить доступ ContentRootPath непосредственно к моему dbcontext. Я жестко запрограммировал путь к моей БД в 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:Default‌​Connection"]));

И я удаляю 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.

Комментарии:

1. Вы уже получаете ее в конструкторе. Зачем вам это нужно OnConfiguring ?

2. У вас есть идея, как получить к нему доступ из конструктора?

3. И как передать ее через параметры в ConfigureServices ?

4. AddDbContext имеет две перегрузки: используемую без параметров и принимающую лямбда-выражение: .AddDbContext(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

5. Я думаю, что я уже пробовал это. Позвольте мне попробовать и вернуться к вам.