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/