我尝试将EF 3.5迁移到6(以sqlite为数据库).我们无法在应用配置文件中设置连接字符串(这在ef6中没有问题).我们必须在运行时以编程方式设置连接字符串(在用户选择了sqlite文件之后).
这是我们的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> <connectionStrings> <add name="testContext" connectionString="data source=Data\testdb.sqlite;Foreign Keys=True" providerName="System.Data.sqlite" /> </connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,EntityFramework"> <parameters> <parameter value="v11.0" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.sqlite" type="System.Data.sqlite.EF6.sqliteProviderServices,System.Data.sqlite.EF6" /> </providers> </entityFramework> <system.data> <DbProviderFactories> <remove invariant="System.Data.sqlite" /> <remove invariant="System.Data.sqlite.EF6" /> <add name="System.Data.sqlite" invariant="System.Data.sqlite" description=".Net Framework Data Provider for sqlite (Entity Framework 6)" type="System.Data.sqlite.EF6.sqliteProviderFactory,System.Data.sqlite.EF6" /> </DbProviderFactories> </system.data> </configuration>
这里是DbContext
public class FirmwareContext : DbContext { public FirmwareContext() : this(DEFAULT_CONNECTION) { } public FirmwareContext(string connextionNameOrString) : base(connextionNameOrString) { } }
如果我连接来自app.config的连接名称,所有的工作都没有问题.如果我尝试传递与第二个构造函数的连接字符串,这将失败
这里是一个小例子
sqliteConnectionStringBuilder builder = factory.CreateConnectionStringBuilder() as sqliteConnectionStringBuilder; builder.DataSource = dataSource; // Path to file name of the user builder.ForeignKeys = true; var context = new FirmwareContext(builder.ToString()); var context = new FirmwareContext(builder.ToString()); var test = context.Firmware.FirstOrDefault();
我得到以下例外(“Schlüsselwortwird nichtunterstützt:”外键“.)=>关键的“外键”不支持.如果我删除外键集,我得到以下异常(“提供程序没有返回一个ProviderManifestToken字符串”)和一些内部异常.
我有同样的问题.通过使用基类DbContext类中的不同构造函数找到了一个解决方法:
public DbContext(DbConnection existingConnection,bool contextOwnsConnection);
使用此覆盖可以传递一个sqliteConnection,而不是设置连接字符串.所以例如你可以添加一个新的构造函数到您的FirmwareContext.
public FirmwareContext(string connectionString) : base(new sqliteConnection() { ConnectionString = connectionString },true) { }
甚至
public FirmwareContext(string filename) : base(new sqliteConnection() { ConnectionString = new sqliteConnectionStringBuilder() { DataSource = filename,ForeignKeys = true } .ConnectionString },true) { }