在内存中使用SQLite运行EF Core - 未配置数据库提供程序

4
我正在编写一个使用 EF Core 和 SQL Server 以及 StructureMap 用于 IOC 的 ASP.Net Core Web API。所有的库项目均为 .NetStandard2.0,而 API 和单元测试则为 NetCoreApp2.0。
对于单元测试,我使用 XUnit,并将 SQL Server 替换为内存中的 SQLite 数据库,因为它提供了完整的引用完整性。我仍然使用与主要代码相同的 IOC 设置,但是我传递了一组 StructureMap 注册表,以便我可以替换 SQLite 上下文工厂而不是 sql 工厂。
这是我 DbContext 的简化版本:
public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions options) : base(options)
    {
    }
}

以下是我的测试代码:

public IServiceProvider ServiceProvider { get; set; }

public MyServiceTests()
{
    var services = new ServiceCollection();
    var dataRegistry = new Registry();

    dataRegistry.For<IContextFactory<MyDbContext>>().Use<SqlLiteContextFactory>();

    if (SqlLiteContextFactory.Connection == null)
    {
        SqlLiteContextFactory.Connection = new SqliteConnection("DataSource=:memory:");
        SqlLiteContextFactory.Connection.Open();
    }

    services
        .AddEntityFrameworkSqlite()
        //This is only here as some posts suggested this was needed, StartUp.cs for production site does not have this and works fine.
        .AddDbContext<MyDbContext>(options => options.UseSqlite(SqlLiteContextFactory.Connection));

    var registries = new List<Registry>
    {
        dataRegistry,
        new CommandQueryRegistry(),
        new ServiceRegistry(),
        new TransformRegistry()
    };

    ServiceProvider = DependencyInjection.TestSetup(services, registries);
}

IOC初始化代码非常基础:

public static IServiceProvider TestSetup(IServiceCollection services, List<Registry> registries)
{
    var container = new Container();

    var registry = new Registry();
    registries.ForEach(r => registry.IncludeRegistry(r));

    container.Configure(config =>
    {
        config.AddRegistry(registry);
        config.ForSingletonOf<IHttpContextAccessor>().Use<HttpContextAccessor>();
        config.Populate(services);
    });

    var serviceProvider = container.GetInstance<IServiceProvider>();
    return serviceProvider;
}

这是我的SQLite上下文工厂的上下文工厂代码,与SQL唯一的区别是我有静态的Connection属性,以确保在上下文被处理后不会失去数据库。
public class SqlLiteContextFactory : IContextFactory<MyDbContext>
{
    public static SqliteConnection Connection;

    private DbContextOptions<MyDbContext> CreateOptions(bool trackChanges)
    {
        var builder = new DbContextOptionsBuilder<MyDbContext>();
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        optionsBuilder.UseSqlite(Connection);

        if (!trackChanges)
        {
            builder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
        }

        return builder.Options;
    }

    private MyDbContext CreateDbContext(bool trackChanges)
    {
        if (Connection == null)
        {
            Connection = new SqliteConnection("DataSource=:memory:");
            Connection.Open();
        }            

        var context = new MyDbContext(CreateOptions(trackChanges));

        //Always keep context as most recent version in tests
        context.Database.Migrate();

        return context;
    }

    public MyDbContext CreateNonTrackedContext()
    {
        return CreateDbContext(false);
    }

    public MyDbContext CreateDbContext()
    {
        return CreateDbContext(true);
    }
}

问题

我的代码在运行站点时很好,SQL上下文工厂创建上下文并运行迁移命令来创建数据库没有问题。 但是,当我尝试通过单元测试测试任何服务时,上下文工厂在尝试运行 Migrate 时会出现以下错误:

System.InvalidOperationException : 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.
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetRelationalService[TService](IInfrastructure`1 databaseFacade)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
   at API.Test.Utilities.SqlLiteContextFactory.CreateDbContext(Boolean trackChanges) in API.Test\Utilities\SqLiteContextFactory.cs:line 37
   at API.Test.Utilities.SqlLiteContextFactory.CreateDbContext() in API.Test\Utilities\SqLiteContextFactory.cs:line 49
   at API.CommandQueries.Commands.MyCommand.AddOrUpdate(MyModel model) in \API.CommandQueries\Commands\MyCommand.cs:line 21
   at API.Services.MyService.Save(Model model) in API.Services\MyService.cs:line 40
   at API.Test.MyTests.CanAdd() in API.Test\MyServiceTests.cs:line 47

我已经尝试了所有我可以找到的解决方法来解决这个问题。将 .AddDbContext 添加到服务集合中。确保测试项目和上下文项目都引用了EntityFrameworkCoreEntityFrameworkCore.RelationalEntityFrameworkCore.Sqlite。确保 SQLite 连接保持存活,并确保测试设置在 ServiceCollection 上使用 .AddEntityFrameworkSqlite()
我还尝试了使用另一个上下文工厂将 SQLite 替换为 EF Core 的 InMemory 数据库,但是遇到了完全相同的问题。
有没有其他人遇到过这个问题,或者我的 EF Core 使用方式使其与 SQLite 不兼容?
1个回答

0

我之前曾经处理过这个问题。我认为你需要运行迁移并保持连接开启状态。你正在覆盖静态连接。此外,我不确定在你使用连接之前是否已创建它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接