Entity framework core: How to test navigation propery loading when use in-memory datastore

旧街凉风 提交于 2019-12-23 13:24:31

问题


There is an interesting feature exists in entity framework core:

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.

This is nice in some cases. However at the current moment I'm trying to modelling many-to-many relation with advanced syntaxic additions and wan't to check, that the mapping I create work well.

But I actually can't do that, since if let's say I have something like:

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);

so due to auto-fixup loaded.Rel field already will be populated, even if I don't include anything. So with this feature I can't actually check nothing. Can't check that I use proper mapping, and my additions to Include works properly. Having thouse in mind, what should I change to be able to actaully test my navigation properties work properly?


I create a testcase which should be passing, but now failing. Exact code could be found there

I'm using .Net Core 2.0 preview 1 and EF core according to that.


回答1:


If you want to test navigation properties with in-memory data store, you need to load your items in "non-tracked" mode, using AsNoTracking() extension.

So, for your case if var loaded = ctx.Model1s.Single(m => m.Id == 777); return you item with relations, than if you rewrite to:
var loaded = ctx.Model1s.AsNoTracking().Single(m => m.Id == 777); this will return you raw item without deps.

So then if you want to check Include again, you could write something like ctx.Model1s.AsNoTracking().Include(m => m.Rel).Single(m => m.Id == 777); and this will return you model with relations you include.



来源:https://stackoverflow.com/questions/44296548/entity-framework-core-how-to-test-navigation-propery-loading-when-use-in-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!