Как программно изменить строку подключения SQLIte DBContext?

Как программно изменить строку подключения SQLIte DBContext?

Цель: сделать чтобы пользователь в процессе работы приложения мог выбирать через диалог разные файлы БД SQLIte.
Как это сделать чтобы после выбора в диалоге менялся путь к БД. Или менять строку подключения в App.config.

Используется:
Nuget: System.Data.SQLite;
Приложение: Console. NET Framework.

Дополнительные библиотеки не хотелось бы устанавливать..
Но если есть необходимость, то можно...

Проект - https://github.com/jhon65496/SqliteConnectStringConslFrmw

введите сюда описание изображения

Способ-1
Если использовать этот способ создания

string path = @"C:\Projects\dbAppIndexes3.db";
string connectionString = $"Data Source={path}";
DbContextIndexes dbContextIndexes = new DbContextIndexes(connectionString);

То код ничего не возвращает.

Способ-2
Если использовать этот способ создания.
Т.е. через изменение App.config, то
GetAll1() нормально отрабатывает, а GetAll2() читает путь к БД из App.config, а путь предыдущий.

GetAll1();
GetAll2();

packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.4.4" targetFramework="net48" />
  <package id="Stub.System.Data.SQLite.Core.NetFramework" version="1.0.118.0" targetFramework="net48" />
  <package id="System.Data.SQLite" version="1.0.118.0" targetFramework="net48" />
  <package id="System.Data.SQLite.Core" version="1.0.118.0" targetFramework="net48" />
  <package id="System.Data.SQLite.EF6" version="1.0.118.0" targetFramework="net48" />
  <package id="System.Data.SQLite.Linq" version="1.0.118.0" targetFramework="net48" />
</packages>

App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
  </startup>
    <connectionStrings>
        <add name="DefaultConnection" connectionString="Data Source=dbAppIndexes.db" providerName="System.Data.SQLite" />
    </connectionStrings>
    <entityFramework>
    <providers>
      <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6"/>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
    <remove invariant="System.Data.SQLite" /><add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" /></DbProviderFactories>
  </system.data>
</configuration>

Index

[Table("Indexes")]
public class Index
{
    public int Id { get; set; }

    public string Name { get; set; }
    
    public string Description { get; set; }        
}

AppService

class AppService
{
    public AppService()
    {
        
        TestMain();
    }



    public void TestMain()
    {
        // Test 1
        // GetAll();
        
        // Test 2
           GetAll1();
           GetAll2();
    }   

    public void GetAll()
    {
        try
        {
            // 
            // string path = @"C:\Projects\dbAppIndexes3.db";
            // string connectionString = $"Data Source={path}";
            // DbContextIndexes dbContextIndexes = new DbContextIndexes(connectionString);


            // 
            string connectionStringsName = "DefaultConnection2";
            DbContextIndexes dbContextIndexes = new DbContextIndexes(connectionStringsName);

            IndexesRepository indexesRepository = new IndexesRepository(dbContextIndexes);

            var i = indexesRepository.Items.ToArray();
            var indexes = new ObservableCollection<Index>(i);
        }
        catch (Exception ex)
        {
            string s = ex.Message;
            throw;
        }            
    }



    public void GetAll1()
    {
        AppSettingService appSettingService = new AppSettingService();
        
        string path = @"C:\Projects\dbAppIndexes3.db";
        string connectionString = $"Data Source={path}";
        string connectionStringName = @"DefaultConnection";

        appSettingService.SaveConnectionString(connectionStringName, connectionString);
        
        DbContextIndexes dbContextIndexes = new DbContextIndexes(connectionStringName);

        IndexesRepository indexesRepository = new IndexesRepository(dbContextIndexes);

        var i = indexesRepository.Items.ToArray();
        var indexes = new ObservableCollection<Index>(i);
    }

    public void GetAll2()
    {
        AppSettingService appSettingService = new AppSettingService();

        string path = @"C:\Projects\dbAppIndexes4.db";
        string connectionString = $"Data Source={path}";
        string connectionStringName = @"DefaultConnection";

        appSettingService.SaveConnectionString(connectionStringName, connectionString);

        DbContextIndexes dbContextIndexes = new DbContextIndexes(connectionStringName);

        IndexesRepository indexesRepository = new IndexesRepository(dbContextIndexes);

        var i = indexesRepository.Items.ToArray();
        var indexes = new ObservableCollection<Index>(i);
    }


}

IndexesRepository

class IndexesRepository 
{

    DbContextIndexes _db;
    #region Конструктор --- --- --- ---
    public IndexesRepository(DbContextIndexes db)
    {
        _db = db;
    }

    #endregion

    public IQueryable<Index> Items => _db.Indexes;

}

DbContextIndexes

public class DbContextIndexes : DbContext
{

    public DbContextIndexes() : base("DefaultConnection")
    {

    }

    
    public DbContextIndexes(string connectionStringsName) : base(connectionStringsName)
    {

    }
    
    public DbSet<Index> Indexes { get; set; }        
}

Program.cs

static void Main(string[] args)
{
    // Console.ReadKey();
    AppService appService = new AppService();
}

Ответы (0 шт):