Search code examples
entity-framework-coretrackingprojection

Can EF Core track entities in non topmost projections?


I have to to load entities (which feature a user_id column) alongside a field of a related table (the name of the user) and I would like my entities to be tracked. Hence I use a projection that encapuslates my entity and that features a property which I assign that field of the related table ... which works as described in the EF Core documentation: https://learn.microsoft.com/en-us/ef/core/querying/tracking#tracking-and-projections.

Now my entity is involved in a 1:n relationship. I need to load the related entities and I also would like to use the same approach as above; alas those entities are not tracked by EF Core.

When I read Top projection should fully materialize and track entities... on the EF Core GitHub page, it gave me the clue that tracking only works for topmost projections, not for projections of related entities.

In the example below, products are tracked, but components are not:

  var entities = context.Products.Select(p =>
      new ProductWrapper
      {
        Entity = p,
        UserName = p.UserNavigation.Name,
        Components = p.Components.Select(c => new ComponentWrapper
        {
          Entity = c,
          UserName = c.UserNavigation.Name
        })
      });

Is this a bug? A missing feature? Any workarounds or better solutions?

In this specific case, I could go for eager loading (via Include()), but that loads the whole User entity (which I don't need). But I'm more interested in an approach that allows me to add any kind of data (like an aggregate value) to my entity: the entity itself is editable by the user (therefore I need tracking), the extra data is read-only.


Solution

  • This may not be the "real solution" but for me it has worked using Include

    This would for you mean this code:

    context.Products.Select
    

    Should become

    context.Products.Include("Components").Select