我正在使用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。
根据微软文档的示例,测试应该类似于:
在我向数据库添加视图后,所有测试都按预期运行,根据此文档: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();
确保数据库已创建,它会根据 protected override void OnModelCreating(ModelBuilder modelBuilder)
中指定的逻辑创建数据库、表和插入关联数据。
问题是,它不会创建视图。 根据文档; 这是预期行为。
我的创建视图的代码与示例代码非常相似:
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();
方法在创建数据库时忽略了迁移文件。
任何帮助将不胜感激。
context.Database.EnsureCreated()
),然后执行RAW SQL (context.Database.ExecuteSqlRaw(<sql>)
)。我们没有那么多的视图,并且我们不希望在这里有太多更改,但如果可能的话,我们想避免这种解决方法,因为它会增加维护工作量。 - Thomas Purrer