EF Core 3.1在Sqlite内存数据库中创建视图以进行测试



我正在使用EF Core 3.1为SqlServer构建数据库模型。我还使用EF生成的迁移文件来处理数据库更改。为了进行测试,我正在内存中旋转Sqlite关系数据库,如微软文档中所述:https://learn.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite.

在我将视图添加到数据库之前,我的所有测试都按预期运行。视图是根据此文档添加的:https://learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-types.

根据微软的文档,一个测试的例子应该是这样的:

[Fact]
public void Add_writes_to_database()
{
// In-memory database only exists while the connection is open
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
try
{
var options = new DbContextOptionsBuilder<BloggingContext>()
.UseSqlite(connection)
.Options;
// Create the schema in the database
using (var context = new BloggingContext(options))
{
context.Database.EnsureCreated();
}
// Run the test against one instance of the context
using (var context = new BloggingContext(options))
{
var service = new BlogService(context);
service.Add("https://example.com");
context.SaveChanges();
}
// Use a separate instance of the context to verify correct data was saved to database
using (var context = new BloggingContext(options))
{
Assert.Equal(1, context.Blogs.Count());
Assert.Equal("https://example.com", context.Blogs.Single().Url);
}
}
finally
{
connection.Close();
}
}

context.Database.EnsureCreated();行确保创建数据库。它创建数据库、表并插入相关数据;根据我的CCD_ 2方法中指定的逻辑。

问题是,它不会创建视图。根据文件;这是预期的行为。

我创建视图的代码看起来非常像示例代码:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<BlogPostsCount>(eb =>
{
eb.HasNoKey();
eb.ToView("View_BlogPostCounts");
eb.Property(v => v.BlogName).HasColumnName("Name");
});
}

我确实手动修改了迁移文件,该文件将使用原始sql创建视图。这在SqlServer上有效,但context.Database.EnsureCreated();方法似乎忽略了创建数据库时的迁移文件。

感谢您的帮助。

基于我非常广泛的研究和测试,我不得不说不,这是不可能的。为自己节省时间和沮丧。

视图在EF Core+SQLite中不受支持,当您通过原始SQL脚本自己注入视图时会发生事件。我做了大量的故障排除,但根本不起作用。

Jimmy Bogard,MediatR&AutoMapper在这篇文章中写到了内存中提供程序的问题,我最终不得不同意他的观点。我基本上发现了同样的问题,只是困难重重。

BTW:如果你认为;好的,我将切换到SQLite文件,然后";,这也于事无补。许多事情变得复杂(DI中DB提供者的数量,对Respawn等第三方库的支持(<也来自Jimmy>(,DbFile上的种族条件

这里的健壮解决方案是容器中的Docker和DB。将你的精力投入到这种方法中。

最新更新