You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Document: OwnedEntities requires AsNoTracking when queried separately #2205
The code below just crashes with "A tracking query projects owned entity without corresponding owner in result. Owned entities cannot be tracked without their owner":
.Select(x => new A
{
OwnedEntity = x.OwnedEntity
});
It worked fine on EF Core 2. No single word about that in the breaking changes doc!
I believe this pattern of querying data is quite often. At least I used to it since EF 6. Adding AsNoTracking() in these cases doesn't make sense for me considering the pattern. I understand it's too late to re-consider but please describe that behavior in the breaking changes at least.
@slipdef What is it that you're trying to do that needs an owned entity tracked without it's owner? In other words, why is it an owned entity if it can exist without its owner?
I didn't need to write that code before EF Core 3:
DbSet.AsNoTracking().Select(x => new A
{
OwnedEntity = x.OwnedEntity
});
I just did
DbSet.Select(x => new A
{
OwnedEntity = x.OwnedEntity
});
and all worked fine.
Now I need because AsNoTracking() is required when querying owned entity without principal. As you pointed out: why would someone need to query owned entity without owner and expect it to be tracked by EF. It doesn't make sense for me too.
Might be worth noting that mapping properties of an Owned Entity Type in a projection will not cause this issue but mapping the Owned Entity Type itself in a projection will, even if properties of the owner are mapped. Examples:
_context.DomainUser.Select(du => new { id = du.Id, Address = du.Address.Line1 }).ToList(); //no exception
_context.DomainUser.Select(du => new { id = du.Id, Address = du.Address }).ToList(); //throws exception
_context.DomainUser.Select(du => new { Address = du.Address.Line1 }).ToList(); //no exception
This really makes Owned Entity Types painful to use when mapping to view models or DTOs.
Reacted by Jos Krause, fvuksan, Kris Vandermotten, dunxz, Filip Herudek, Doug Waldron, David Ferretti and Lucas Eduardo Ormond de Sousa
Above query is marked as tracking by default. If you project Customer, we have enough data to update Address also.
If customer is not projected then we are left with Address & City entity. Address cannot be updated without Customer so it create first confusion point, would City be tracked (making only owned entity non-tracked or City won't be tracked (making whole query non-tracking).
If only owned entities are skipped then user who is updating owned entity values would have changes saved sometimes (if owner is also projected or values won't be saved). Also creates another odd behavior that if owner is already in change tracker and owned entity is queried, it may be saved.
If query becomes non-tracking then City won't be saved. By far, City is neither owned nor part of aggregate, having it's behavior vary is hard to predict.
Overall, making implicit non-tracking forces users to understand what case it would be tracked vs non-tracked with above set of complex rules, alongwith potential of data loss if something is not saved correctly.
By making AsNoTracking required explicitly, users would know when they are querying owned entity which cannot be updated. So they can take corrective action based on what usage they want. Further, by putting explicit AsNoTracking it becomes clearer that what happens to unrelated entities like City in such queries.
Reacted by Arthur Vickers, Philipp Drebes, dunxz, CrazyTim and Lucas Eduardo Ormond de Sousa
changed the title [-]Not documented breaking change: OwnedEntities requires AsNoTracking when queried separately[/-][+]Document: OwnedEntities requires AsNoTracking when queried separately[/+]on Mar 20, 2020
I have a domain layer that is provided with an IQueryable<TAggregate> that in reality is a DbSet<TAggregate> created by the persistence layer. The domain layer now wants to do such a projection but out of a sudden gets an Exception, that yesterday wasn't there.
Plus: The domain layer has no idea what Entity Framework is. It is persistence agnostic, so there is no .AsNoTracking(). I am basically forced to do a load of the whole table into memory, just to prevent someone who copies code from the documentation without reading the documentation to shoot themseves into the foot.
Sadly, this is a recurrent pattern with Entity Framework Core: you spent too much energy on the "Demoware" use cases, but leave behind the serious architectual concepts like domain driven design. Don't get me wrong, I really love EF Core, but the time I spent to make thing such as an aggregate working is really high and I start thinking that an implementation at lower level like Dapper would be easier in the end, and using EF Core only as query implementation as the Q in CQRS
One of our customers reported this error, though the scenario is slightly different. JsonApiDotNetCore dynamically produces LINQ queries of the following form when the API request contains sparse fieldsets (basically selecting a subset of the entity properties and navigations).
When no owned entities are involved, this works without explicitly setting a tracking behavior. The entities won't get tracked (obviously), which is fine because we only do this on read-only requests. But when owned entities are used, we now need to explicitly mark the query as non-tracking.
I understand that the rules when tracking occurs are complex, but the current experience is pretty inconsistent: We've all been building queries for years that weren't trackable, and we never cared. Now we suddenly need to rationalize and specify when we want to track or not, which is a pain because it may heavily affect performance. It would make more sense to me to downgrade this exception to a warning, which we can suppress in configuration. As a workaround, we're now setting the tracking behavior to NoTrackingWithIdentityResolution for all read-only requests.
Aside from that, in our example query there is actually an owner, so the error message does not seem to apply. Is this a bug?
Note from triage: we discussed this again, but we still believe that the error is useful for preventing people falling into a pit of failure with tracking queries. We are not going to make changes here.
I don't get this. We cannot track primitives or anonymous types either but we don't explode if we happen to project to something else untrackable; why should these explode? .AsNoTracking() is not possible when I am outside of EF with an IQueryable (unless I really had to add it to my interfaces; but that is 'leaky').
I would think the Owned Entity should just be seen as a named set of fields and if I project to it then I am effectively projecting to those fields (which I could do manually already right? but I would throw away the functionality in my type for no reason).
I don't get the reason for the error; I already know my type is not a full entity and that I would lose tracking by narrowing to it; but there are lots of queries where that is true and they don't explode...
Reacted by j-roba, Doug Waldron, Lucas Eduardo Ormond de Sousa and Xriuk
IMHO another tracking behaviour should be added, where projected Non-owned entities are tracked (with or without identity resolution), while projected owned entities are not tracked.
AsNoTracking is not always possible because the IQueryable might be generated and contain both, and we would want to use lazy loaders on entities.
Or entities could be tracked into projections automatically, because if we know which owned entity we are projecting we might be able to track back the original entity and retrieve it and track but without including it in the projection, shadow-like.
Activity
ajcvickers commentedon Nov 14, 2019
@slipdef What is it that you're trying to do that needs an owned entity tracked without it's owner? In other words, why is it an owned entity if it can exist without its owner?
slipdef commentedon Nov 14, 2019
I indeed don't need an owned entity being tracked without owner. So I would be totally fine if AsNoTracking() is added by default in such cases.
ajcvickers commentedon Nov 14, 2019
@slipdef In that case can you elaborate on, "adding AsNoTracking() in these cases doesn't make sense for me."
slipdef commentedon Nov 14, 2019
I didn't need to write that code before EF Core 3:
I just did
and all worked fine.
Now I need because AsNoTracking() is required when querying owned entity without principal. As you pointed out: why would someone need to query owned entity without owner and expect it to be tracked by EF. It doesn't make sense for me too.
ajcvickers commentedon Nov 14, 2019
@slipdef Thanks; we will discuss.
ajcvickers commentedon Nov 15, 2019
We discussed in triage and decided to keep this on the backlog to consider not requiring AsNoTracking in this case.
@smitpatel Can you write down something that explains the main reason owned types can be more confusing than other non-tracked objects.
AndriySvyryd commentedon Dec 4, 2019
Adding
AsNoTrackingimplicitly wouldn't prevent the breaking change if the code relied on them being tracked.joelmdev commentedon Dec 4, 2019
Might be worth noting that mapping properties of an Owned Entity Type in a projection will not cause this issue but mapping the Owned Entity Type itself in a projection will, even if properties of the owner are mapped. Examples:
_context.DomainUser.Select(du => new { id = du.Id, Address = du.Address.Line1 }).ToList(); //no exception_context.DomainUser.Select(du => new { id = du.Id, Address = du.Address }).ToList(); //throws exception_context.DomainUser.Select(du => new { Address = du.Address.Line1 }).ToList(); //no exceptionThis really makes Owned Entity Types painful to use when mapping to view models or DTOs.
smitpatel commentedon Dec 5, 2019
With model
Query
Above query is marked as tracking by default. If you project Customer, we have enough data to update Address also.
Overall, making implicit non-tracking forces users to understand what case it would be tracked vs non-tracked with above set of complex rules, alongwith potential of data loss if something is not saved correctly.
By making AsNoTracking required explicitly, users would know when they are querying owned entity which cannot be updated. So they can take corrective action based on what usage they want. Further, by putting explicit AsNoTracking it becomes clearer that what happens to unrelated entities like City in such queries.
[-]Not documented breaking change: OwnedEntities requires AsNoTracking when queried separately[/-][+]Document: OwnedEntities requires AsNoTracking when queried separately[/+]2 remaining items
marcwittke commentedon Jul 1, 2022
I have a domain layer that is provided with an
IQueryable<TAggregate>that in reality is aDbSet<TAggregate>created by the persistence layer. The domain layer now wants to do such a projection but out of a sudden gets an Exception, that yesterday wasn't there.Plus: The domain layer has no idea what Entity Framework is. It is persistence agnostic, so there is no
.AsNoTracking(). I am basically forced to do a load of the whole table into memory, just to prevent someone who copies code from the documentation without reading the documentation to shoot themseves into the foot.Sadly, this is a recurrent pattern with Entity Framework Core: you spent too much energy on the "Demoware" use cases, but leave behind the serious architectual concepts like domain driven design. Don't get me wrong, I really love EF Core, but the time I spent to make thing such as an aggregate working is really high and I start thinking that an implementation at lower level like Dapper would be easier in the end, and using EF Core only as query implementation as the Q in CQRS
bkoelman commentedon May 10, 2023
One of our customers reported this error, though the scenario is slightly different. JsonApiDotNetCore dynamically produces LINQ queries of the following form when the API request contains sparse fieldsets (basically selecting a subset of the entity properties and navigations).
When no owned entities are involved, this works without explicitly setting a tracking behavior. The entities won't get tracked (obviously), which is fine because we only do this on read-only requests. But when owned entities are used, we now need to explicitly mark the query as non-tracking.
I understand that the rules when tracking occurs are complex, but the current experience is pretty inconsistent: We've all been building queries for years that weren't trackable, and we never cared. Now we suddenly need to rationalize and specify when we want to track or not, which is a pain because it may heavily affect performance. It would make more sense to me to downgrade this exception to a warning, which we can suppress in configuration. As a workaround, we're now setting the tracking behavior to
NoTrackingWithIdentityResolutionfor all read-only requests.Aside from that, in our example query there is actually an owner, so the error message does not seem to apply. Is this a bug?
ajcvickers commentedon May 11, 2023
@bkoelman We will discuss.
ajcvickers commentedon Jul 8, 2023
Note from triage: we discussed this again, but we still believe that the error is useful for preventing people falling into a pit of failure with tracking queries. We are not going to make changes here.
Workaround for dotnet/EntityFramework.Docs#2205
DaveCousineau commentedon Jun 20, 2024
I don't get this. We cannot track primitives or anonymous types either but we don't explode if we happen to project to something else untrackable; why should these explode?
.AsNoTracking()is not possible when I am outside of EF with anIQueryable(unless I really had to add it to my interfaces; but that is 'leaky').I would think the Owned Entity should just be seen as a named set of fields and if I project to it then I am effectively projecting to those fields (which I could do manually already right? but I would throw away the functionality in my type for no reason).
I don't get the reason for the error; I already know my type is not a full entity and that I would lose tracking by narrowing to it; but there are lots of queries where that is true and they don't explode...
Explicitly set query projection queries as no-tracking
Add repository overloads with query projection (#57)
Xriuk commentedon Jul 31, 2026
IMHO another tracking behaviour should be added, where projected Non-owned entities are tracked (with or without identity resolution), while projected owned entities are not tracked.
AsNoTracking is not always possible because the IQueryable might be generated and contain both, and we would want to use lazy loaders on entities.
Or entities could be tracked into projections automatically, because if we know which owned entity we are projecting we might be able to track back the original entity and retrieve it and track but without including it in the projection, shadow-like.