Ste*_*ven 7 c# testing entity-framework ef-core-3.1
我正在使用 EF Core 3.1 为 SqlServer 构建我的数据库模型。我还使用 EF 生成的迁移文件来处理数据库更改。为了进行测试,我正在按照微软文档中的描述启动内存中的 Sqlite 关系数据库:https : //docs.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite。
我所有的测试都按预期运行,直到我将视图添加到我的数据库中。根据此文档添加了视图:https : //docs.microsoft.com/en-us/ef/core/modeling/keyless-entity-types。
根据 Microsoft 文档,测试示例应如下所示:
[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();
}
}
Run Code Online (Sandbox Code Playgroud)
该行context.Database.EnsureCreated();确保创建数据库。它创建数据库、表并插入相关数据;根据我的protected override void OnModelCreating(ModelBuilder modelBuilder)方法中指定的逻辑。
问题是,它不会创建 View。根据文件;这是预期的行为。
我创建视图的代码与示例代码非常相似:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<BlogPostsCount>(eb =>
{
eb.HasNoKey();
eb.ToView("View_BlogPostCounts");
eb.Property(v => v.BlogName).HasColumnName("Name");
});
}
Run Code Online (Sandbox Code Playgroud)
我确实手动修改了将使用原始 sql 创建视图的迁移文件。这适用于 SqlServer,但该context.Database.EnsureCreated();方法似乎忽略了创建数据库时的迁移文件。
任何帮助表示赞赏。
根据我非常广泛的研究和测试,我不得不说不,这是不可能的。节省自己的时间和挫败感。
当您通过原始 SQL 脚本自行注入视图时,EF Core + SQLite 中不支持视图功能。我做了非常广泛的故障排除,但它根本不起作用。
MediatR 和 AutoMapper 的作者Jimmy Bogard在这篇文章中写了内存提供程序的问题,我最终不得不同意他的观点。我基本上发现了同样的问题,只是很难。
顺便说一句:如果您认为“好吧,那么我将切换到 SQLite 文件”,这也没有多大帮助。许多事情变得复杂( DI 中的数据库提供程序数量、对 Respawn(也来自 Jimmy )等第三方库的支持、DbFile 上的竞争条件)。
这里强大的解决方案是容器中的 Docker 和数据库。将你的精力投入到这种方法中。
| 归档时间: |
|
| 查看次数: |
543 次 |
| 最近记录: |