Entity Infrastructure Kernel: How to Verify the Right Navigation Load When Using In-Memory

An interesting function exists in the core of entity structures:

Entity Framework Core will automatically set navigation properties to any other objects that were previously loaded into the example context. Therefore, even if you do not explicitly include data for the navigation property, the property can still be populated if some or all of the related objects have been loaded before.

This is good in some cases. However, at the moment I am trying to model a many-to-many relationship with advanced syntactic additions and not verify that the generated mapping works well.

But I really canโ€™t do this, because if I say that 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 because of the auto-fixup loaded.Rel loaded.Rel will already be filled even if I donโ€™t add anything. Therefore, with this function, I can not verify anything. I canโ€™t verify that I am using the correct mapping, and my additions to Include work correctly. Bearing in mind that I have to change in order to be able to effectively validate my navigation properties correctly?


I am creating a test file that should pass, but now does not work. The exact code can be found there.

I am using .Net Core 2.0 1 preview and EF core.

+2
source share
1 answer

If you want to check the properties of navigation with a data warehouse in memory, you need to load your objects in "no tracking" mode using the AsNoTracking() extension.

So, for your case, if var loaded = ctx.Model1s.Single(m => m.Id == 777); returns you an element with relations than if you rewrite:
var loaded = ctx.Model1s.AsNoTracking().Single(m => m.Id == 777); This will return you the raw item without a depot.

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

+4
source

Source: https://habr.com/ru/post/1268400/


All Articles