Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 837
silent_coder Avatar asked Mar 09 '23 23:03

silent_coder


1 Answers

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.

like image 70
Ph0en1x Avatar answered Mar 25 '23 17:03

Ph0en1x