Skip to content

Lazy one-to-one entity changes lost when invoking navigation property #23757

@markhobson

Description

@markhobson

Problem

I have the following example entity model:

 Blog
  |   1..1
 Post
 /|\  1..m
Image

(Note the relationship between Blog and Post is one-to-one which is a deviation from the usual example model.)

Lazy-loading is enabled on all navigation properties. I then perform the following operations using separate DbContexts:

  1. Create a new Blog with a Post titled "A"
  2. Fetch the Blog, replace its Post with a new entity titled "B", and then add an Image to the Post
  3. Fetch the Post and display its title

I would expect the Post title to be "B" but it is actually "A".

Please see markhobson/ef-issue to reproduce this problem.

Observations

It appears that EF notices the Post has changed:

dbug: 23/12/2020 09:35:19.238 CoreEventId.ReferenceChangeDetected[10805] (Microsoft.EntityFrameworkCore.ChangeTracking) 
      The navigation 'Blog.Post' for entity with key '{Id: 5}' was detected as changed.
dbug: 23/12/2020 09:35:19.239 CoreEventId.ValueGenerated[10808] (Microsoft.EntityFrameworkCore.ChangeTracking) 
      'BloggingContext' generated temporary value '-2147482646' for the property 'Id.Post'.
dbug: 23/12/2020 09:35:19.240 CoreEventId.StartedTracking[10806] (Microsoft.EntityFrameworkCore.ChangeTracking) 
      Context 'BloggingContext' started tracking 'Post' entity with key '{Id: -2147482646}'.

It then proceeds to lazy-load the Posts relationship which detaches the new Post entity:

dbug: 23/12/2020 09:35:19.254 CoreEventId.StartedTracking[10806] (Microsoft.EntityFrameworkCore.ChangeTracking) 
      Context 'BloggingContext' started tracking 'Post' entity with key '{Id: 6}'.
dbug: 23/12/2020 09:35:19.262 CoreEventId.CascadeDeleteOrphan[10003] (Microsoft.EntityFrameworkCore.Update) 
      An entity of type 'Post' with key '{Id: -2147482646}' changed to 'Detached' state due to severed required relationship to its parent entity of type 'Blog'.
dbug: 23/12/2020 09:35:19.264 CoreEventId.StateChanged[10807] (Microsoft.EntityFrameworkCore.ChangeTracking) 
      The 'Post' entity with key '{Id: -2147482646}' tracked by 'BloggingContext' changed state from 'Added' to 'Detached'.

Which results in the old Post entity being persisted with the new Images.

This seems to only be an issue when:

  • Lazy-loading is enabled
  • The Images relationship is updated

Workaround

If the Post relationship is invoked before replacement then it is persisted correctly. Please see the code for details.

Provider and version information

EF Core version: 5.0.1
Database provider: Microsoft.EntityFrameworkCore.Sqlite
Target framework: .NET Core 3.1
Operating system: Ubuntu 20.04
IDE: Rider 2020.3

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions