I noticed that when I navigate to the same entity object via a different "member path" I get a different object. (I'm using change-tracking proxies, so I get a different change-tracking proxy object.)
Here is an example to show what I mean.
var joesInfo1 = context.People.Single(p => p.Name == "Joe").Info;
var joesInfo2 = context.People.Single(p => p.Name == "Joe's Dad").Children.Single(p => p.Name == "Joe").Info;
Even though joesInfo1 & joesInfo2 refer to the same record in the DB (the same entity), they are different objects. I thought that Entity Framework made sure to use the same object in these cases.
Question #1: Is this really how it is? Or is my observation wrong?
This is a problem when eager loading via Include. For example,
IQueryable<Person> allPeople = null;
using(context)
{
allPeople = context.People
//.AsNoTracking()
.Include(p => p.Info)
.Include(p => p.Children)
.Include(p => p.Parent)
.ToList();
}
var joesInfo1 = allPeople.Single(p => p.Name == "Joe").Info; // OK, Info is already there because it was eagerly loaded
var joesInfo2 = allPeople.Single(p => p.Name == "Joe's Dad").Children.Single(p => p.Name == "Joe").Info;
// ERROR: "Object context disposed...", Info is not in the Person object, even though the Person object refers to the same entity (Joe) as above.
So, it looks like to get eager loading to work, you have to specify all possible "member access paths" that you will take in your program. This is not possible in some cases like this one. Because your Person object might be floating around in your program and the navigation properties "Parent" or "Children" could be called on it (and it's parents/children) any number of times.
Question #2: Is there any way to get this to work without specifying all of the "member access paths" that you will take in your program?
Thanks.
ANSWER:
So, here's what I have concluded, based on bubi's answer.
It is possible to get different "entity objects" if you use AsNoTracking(). (In other words, in the example above, depending on what path you take to get to the "Joe" Person entity, it's possible that you will get a different object.) If you don't use AsNoTracking all the Joes will be the same object.
Here is what this means:
You CAN eagerly load a whole hierarchical or recursive object graph and use it outside of a context. How? JUST DON'T USE AsNoTracking().
using
scope will throw because nothing get loaded before the query is executed. Please provide the full sample entity model with fluent configuration if any and minimal reproducible example. – Ivan Stoev Aug 2 '17 at 20:11