【发布时间】:2016-12-09 13:59:53
【问题描述】:
在我开始之前,现有的问题here 和here 并不能解决我的问题。
我正在使用带有 EF6 的 SQLite,包 SQLite.CodeFirst 用于根据需要生成我的数据库架构。我正在我的存储库类上运行单元测试,它在后端使用 DBContext,但是在运行每个测试之前需要清理数据库,以便后续测试不会损坏。
我的问题是当我调用 dbContext.Database.Delete() 时出现以下异常:
System.Data.Entity.Core.ProviderIncompatibleException was unhandled by user code
Message=DeleteDatabase is not supported by the provider.
Source=EntityFramework
我想避免尝试发现数据库的位置并将其从磁盘中删除,因为位置因应用程序而异。有人有什么建议吗?
以下是我的代码相关部分的摘录:
App.config
<entityFramework>
<providers>
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6, Version=1.0.103.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
<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>
<connectionStrings>
<add name="EngineDataContext_LocalDb" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=Engine.DataModel.EngineDataContext;MultipleActiveResultSets=True;Integrated Security=True;App=EntityFramework" providerName="System.Data.SqlClient" />
<add name="EngineDataContext_SQLServer" connectionString="Data Source=.;Initial Catalog=Engine.DataModel.EngineDataContext;MultipleActiveResultSets=True;Integrated Security=True;" providerName="System.Data.SqlClient" />
<add name="EngineDataContext_SQLite" connectionString="Data Source=.\database.sqlite" providerName="System.Data.SQLite" />
</connectionStrings>
<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>
数据上下文
public class EngineDataContext : DbContext
{
public EngineDataContext()
: base("name=EngineDataContext_SQLite")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var sqliteConnectionInitializer = new SqliteDropCreateDatabaseAlways<EngineDataContext>(modelBuilder);
Database.SetInitializer(sqliteConnectionInitializer);
}
}
存储库
public class SqliteRepository
{
private readonly EngineDataContext _dataContext;
public SqliteRepository(EngineDataContext dataContext)
{
_dataContext = dataContext;
}
public void DropCreateDatabase()
{
_dataContext.Database.Delete(); // FAIL
_dataContext.Database.Create();
}
}
【问题讨论】:
-
我认为问题是在SQLite中删除数据库没有意义,所以你只能删除文件。
标签: entity-framework sqlite ef-code-first entity-framework-6