问题描述
我有一个测试装置,在其中初始化我的SQLite内存dbcontext,如下所示:
I have a test fixture in which I initialize my SQLite in-memory dbcontext, shown below:
public static MYAPPDBContext Create()
{
var options = new DbContextOptionsBuilder<MYAPPDBContext>()
.UseSqlite("DataSource=:memory:")
.Options;
var context = new MYAPPDBContext(options);
context.Database.OpenConnection(); // this is where exception is thrown
context.Database.EnsureCreated();
return context;
}
当我调用Create()方法时,得到以下NullReferenceException:
When I call the Create() method, I get the following NullReferenceException:
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=Microsoft.Data.Sqlite
StackTrace:
at Microsoft.Data.Sqlite.SqliteConnection.Open()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteRelationalConnection.Open(Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.<>c.<OpenConnection>b__15_0(DatabaseFacade database)
at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, Func`2 verifySucceeded, TState state)
at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.OpenConnection(DatabaseFacade databaseFacade)
at MYAPPPlus.UnitTests.TestInfrastructure.MYAPPContextFactory.Create() in C:\websites\MYAPPPremier\tests\MYAPPPlus.UnitTests\TestInfrastructure\MYAPPContextFactory.cs:line 26
at MYAPPPlus.UnitTests.TestInfrastructure.QueryTestFixture..ctor() in C:\websites\MYAPPPremier\tests\MYAPPPlus.UnitTests\TestInfrastructure\QueryTestFixture.cs:line 24
关于可能发生的事情的任何想法吗?
Any ideas on what might be happening?
仅供参考:我将代码建立在 https://garywoodfine.com/entity-framework-core-memory-testing-database/,以及其他资源.而且,当使用基本的ef核心内存数据库时,我的夹具也可以正常工作.
FYI: I'm basing my code on the blog post at https://garywoodfine.com/entity-framework-core-memory-testing-database/, among other resources.Also, my fixture works just fine when using basic ef core inmemory database.
推荐答案
我的糟糕.当我需要版本2.2.6时,我已经安装了Microsoft.Data.Sqlite.Core版本3.0.0,而我没有安装此后就已经安装的Microsoft.Data.Sqlite.2.6.2.现在正在工作.
My bad. I had installed Microsoft.Data.Sqlite.Core version 3.0.0 when I needed version 2.2.6 and I had not installed Microsoft.Data.Sqlite 2.2.6, which I have since installed. It's working now.
仅供参考:.UseSqlite("Data Source =:memory:")和.UseSqlite("DataSource =:memory:")都可以工作.
Also, FYI: both .UseSqlite("Data Source=:memory:") and .UseSqlite("DataSource=:memory:") work.
这篇关于ASP.NET Core测试-在Fixture中初始化InMemory SQLite dbcontext时获取NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!