asp.net-core - Entity Framework 核心 : How to test navigation propery loading when use in-memory datastore

标签 asp.net-core entity-framework-core navigation-properties

Entity Framework 核心中有一个有趣的特性:

Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.



这在某些情况下很好。但是,目前我正在尝试使用高级语法添加对多对多关系进行建模,并且不想检查我创建的映射是否运行良好。

但我实际上不能那样做,因为如果让我们说我有类似的东西:
class Model1{
   ... // define Id and all other stuff
   public ICollection<Model2> Rel {get; set;}
}

Model1 m1 = new Model1(){Id=777};
m1.Rel.Add(new Model2());
ctx.Add(m1);
ctx.SaveChanges()

var loaded = ctx.Model1s.Single(m => m.Id == 777);

所以由于自动修复 loaded.Rel字段已经被填充,即使我不包含任何内容。因此,使用此功能,我实际上无法检查任何内容。无法检查我是否使用了正确的映射,以及我对 Include 的补充工作正常。考虑到 thouse,我应该更改什么才能实际测试我的导航属性是否正常工作?

我创建了一个应该通过的测试用例,但现在失败了。 Exact code could be found there

我正在使用 .Net Core 2.0 preview 1 和 EF core 据此。

最佳答案

如果要使用内存数据存储测试导航属性,则需要使用 AsNoTracking() 以“非跟踪”模式加载项目。延期。

所以,对于你的情况,如果var loaded = ctx.Model1s.Single(m => m.Id == 777);返回带有关系的项目,而不是重写为:var loaded = ctx.Model1s.AsNoTracking().Single(m => m.Id == 777);这将返回您没有 deps 的原始项目。

那么如果你想检查Include再次,你可以写类似 ctx.Model1s.AsNoTracking().Include(m => m.Rel).Single(m => m.Id == 777); 的内容这将返回您包含关系的模型。

关于asp.net-core - Entity Framework 核心 : How to test navigation propery loading when use in-memory datastore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44296548/

相关文章:

c# - 始终执行条件中间件

c# - 带有 F# : System. InvalidOperationException 的 Swashbuckle:'无法找到所需的服务

c# - EF 核心中的自引用错误 : the insert statement conflicted with the foreign key same table constraint

c# - GroupBy 查询和位字段

c# - Entity Framework - n 层 - 多对多 - 如何获取列表 "where"

c# - 从 ASP.NET Core 1.1 MVC 迁移到 2.0 后自定义 cookie 身份验证不起作用

c# - 如何将通用基本 Controller 与 ActionFilters 一起使用

sql-server - Entity Framework 核心在 c# 中将 float(db 数据类型)转换为 double 时添加数字

entity-framework - EF5 如何获取域对象的导航属性列表

c# - Entity Framework 导航属性上的 .Skip().Take() 正在我的 SQL Server 上执行 SELECT *