Entity framework core 首先使用InMemory数据库和EntityFramework核心代码测试视图
我有一个EF核心代码第一个web api应用程序 有一个Products实体和一个UserProductsRating子实体(具有一对多关系) 我还希望有一个平均的评论分数(并且能够根据它进行选择/排序),所以创建了一个视图来实现这一点(使用这个答案中描述的方法) [) 因此,我的视图的迁移如下所示:Entity framework core 首先使用InMemory数据库和EntityFramework核心代码测试视图,entity-framework-core,asp.net-core-webapi,xunit,in-memory-database,Entity Framework Core,Asp.net Core Webapi,Xunit,In Memory Database,我有一个EF核心代码第一个web api应用程序 有一个Products实体和一个UserProductsRating子实体(具有一对多关系) 我还希望有一个平均的评论分数(并且能够根据它进行选择/排序),所以创建了一个视图来实现这一点(使用这个答案中描述的方法) [) 因此,我的视图的迁移如下所示: protected override void Up(MigrationBuilder migrationBuilder) { str
protected override void Up(MigrationBuilder migrationBuilder)
{
string script =
@"
CREATE VIEW AverageProductRating AS
SELECT u.ProductId, AVG(CAST(u.Rating AS FLOAT)) as AverageRating
FROM dbo.UserRatings u GROUP BY u.ProductId";
migrationBuilder.Sql(script);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
string script = @"DROP VIEW dbo.AverageProductRating";
migrationBuilder.Sql(script);
}
然后在顶部有一个平均实体
这一切都很好,允许我创建如下查询:
var top5Products = _db.Products.Include(x => x.AverageProductRating)
.Where(x => x.AverageProductRating != null)
.OrderByDescending(x => x.AverageProductRating.AverageRating)
.Take(5);
当我进行单元/集成测试时,问题就出现了。我正在使用InMemoryDatabase和EnsureCreated来设置测试实例/种子数据
var options = new DbContextOptionsBuilder<ProductsContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.EnableSensitiveDataLogging()
.Options;
var context = new ProductsContext(options);
context.Database.EnsureCreated();
var options=new DbContextOptionsBuilder()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.EnableSensitiveDataLogging()
.选择;
var context=新产品上下文(选项);
context.Database.recreated();
当我对该视图运行测试时,AverageProductRating实体总是有零行(我不确定是否创建了该视图)
我认为这可能与inmemory db中SQL的限制或迁移的运行方式有关,但我不确定
欢迎就如何解决这一问题提出任何建议
谢谢