0

I have a scenario where a Manager (Employee table) has several Desktops (Desktop table) and several Reportees (Employee table using self reference). I am using EF Core 1.x.

I have Desktop Id and Reportee Id as inputs and I want to retrieve Manager obkect filled with one Desktop object and one Reportee (Employee) object pertaining to supplied ids as expected output. So, I wrote following query:

var desktop = _desktopRepository.Query()
    .Where(s => s.Id == desktopId)
    .Include(s => s.Employee)
    .All()
    .FirstOrDefault();

// EF is magically adding reportee object to the desktop.Employee.Reportee list.
// So, no need to add it separately. If done, there'll be two objects of same Reportee.
var reportee = _employeeRepository.Get(reporteeId).Result;

What I observed here is written in comments. I am looking for guidance on why is EF automatically adding this object to the list.

It is important to note that here, I am firing two completely different queries. When I debug through the code, I find that it is firing them separately and fetching the result. The EF is not only adding the result into above entity, but also returning it as independent result.

NOTE: Sorry, but I am not looking if this is right or wrong approach. But I want to know how/why EF is adding this object automatically to the collection.

Any help is much appreciated. Many thanks in Advance.

Abhi
  • 1,624
  • 2
  • 16
  • 29
  • The answer to the linked post contains a link to the EF Core documentation explaining that behavior. – Ivan Stoev Sep 12 '17 at 11:10
  • Hi Ivan, thanks for pointing to the interesting documentation. However, I added comment (in italics). Unlike the referenced question, my code is dealing with two distinct queries but their results getting mixed. Does the documentation still answer this? If EF is eager loading the data, shouldn't the second SQL query be fired with the first one? What I am observing is when the second query is called, the results are merged to first query results. Which is semantically absurd. – Abhi Sep 15 '17 at 09:08
  • Hi @Abhi, You are welcome. Probably you are missing the fact that both repositories most likely share one and the same `DbContext` instance. And EF context internally keeps track of all objects retrieved from the database by one or more independent queries. So anytime any query generates an object during its materialization, the context is searching for loaded related entities and performs "fixup", .e.g. set the related reference property, add object to related collection etc. While the result set of the query is not modified, the content of the objects is. Hope that explains it. – Ivan Stoev Sep 15 '17 at 10:16
  • Thanks Ivan, yet again! And yes that explains it; they do share the same `DbContext`. Although I thought on similar lines, I thought I will get clarified. :) – Abhi Sep 16 '17 at 01:26

0 Answers0