如何以编程方式更改 SQLite DbContext 连接字符串?
目标:让用户在应用程序过程中可以通过对话框选择不同的SQLite数据库文件。
如何执行此操作,以便在对话框中选择后,数据库的路径会发生变化。
或者更改 App.config 中的连接字符串。
使用:
Nuget: System.Data.SQLite;
应用程序:控制台。 NET 框架。
我不想安装额外的库..
但如果有需要的话,你可以...
项目 - https://github.com/jhon65496/SqliteConnectStringConslFrmw
方法1
如果你使用这种创建方法
string path = @"C:\Projects\dbAppIndexes3.db";
string connectionString = $"Data Source={path}";
DbContextIndexes dbContextIndexes = new DbContextIndexes(connectionString);
那么代码不会返回任何内容。
方法2
如果你使用这种创作方法。
IE。通过更改 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>
应用程序配置
<?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>
索引
[Table("Indexes")]
public class Index
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
应用服务
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);
}
}
索引存储库
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; }
}
程序.cs
static void Main(string[] args)
{
// Console.ReadKey();
AppService appService = new AppService();
}
对于 EF6(.Net Framework),选项 1 应该可以工作,因为您可以向它传递 ConnectionStringName(来自 app.config)或 ConnectionString。但是,如果传递连接字符串,则需要确保它是完整且有效的连接字符串。在您的示例中,您没有传递提供程序,如果您只想使用默认配置的提供程序并覆盖连接字符串,有一个简单的解决方法:
string path = @"C:\Projects\dbAppIndexes3.db";
string connectionString = $"Data Source={path}";
DbContextIndexes dbContextIndexes = new DbContextIndexes(connectionString);
public DbContextIndexes() : base("DefaultConnection")
{ }
public DbContextIndexes(string connectionString) : this () // Use "DefaultConnection" app connection string and provider...
{
Database.Connection.ConnectionString = connectionString; // Overwrite to use the desired connection string.
}
如果您想支持在不同的提供程序之间进行选择,您可以执行类似的操作,提供提供程序枚举以在连接字符串旁边的 SqlLite、SQL Server 等之间进行选择,然后为每个提供程序创建默认配置,例如 DefaultSqlLiteConnection 和 DefaultSqlServerConnection 等。在配置文件中:
public DbContextIndexes(DbProvider provider, string connectionString)
: base(provider == DbProvider.SqlServer ? "DefaultSqlServerConnection" : "DefaultSqlLiteConnection")
{
Database.Connection.ConnectionString = connectionString;
}