Skip to content

Detaching an entity results in related entities being deleted #18982

Closed

Description

EF Core 3.0.1

I insert an object along with related objects. Then I set the state of the object to "Detached". I then perform another call to .SaveChangesAsync().

Observed behavior: the related objects are deleted.
Expected behavior: the related objects should not be deleted; rather their tracking status should simply be set to "Detached".

(This is a breaking change since upgrading from EF Core 2.2.4)

Steps to reproduce

    public class Thing
    {
        [Key]
        public Guid ThingId { get; set; }
        [MaxLength(200)]
        public string Description { get; set; }
        public List<OwnedByThing> OwnedByThings { get; set; } = new List<OwnedByThing>();
    }

    public class OwnedByThing
    {
        [Key]
        public Guid OwnedByThingId { get; set; }
        public Guid ThingId { get; set; }
        public Thing Thing { get; set; }
        public int Value { get; set; }
    }

            await using var db = new MyDbContext();
            var thing = new Thing
            {
                Description = "Hello world thing",
                OwnedByThings = new List<OwnedByThing>
                {
                    new OwnedByThing {Value = 1},
                    new OwnedByThing {Value = 2}
                }
            };

            db.Things.Add(thing);
            await db.SaveChangesAsync();

            var thingCount = await db.Things.CountAsync(e => e.ThingId == thing.ThingId);
            Assert.AreEqual(1, thingCount, "Thing Count A");
            var ownedCount = await db.OwnedByThings.CountAsync(e => e.ThingId == thing.ThingId);
            Assert.AreEqual(2, ownedCount, "Owned count A");

            db.Entry(thing).State = EntityState.Detached;
            await db.SaveChangesAsync();
            
            thingCount = await db.Things.CountAsync(e => e.ThingId == thing.ThingId);
            Assert.AreEqual(1, thingCount, "Thing Count B");
            ownedCount = await db.OwnedByThings.CountAsync(e => e.ThingId == thing.ThingId);
            Assert.AreEqual(2, ownedCount, "Owned count B");

Result:

  Owned count B
  Expected: 2
  But was:  0

Further technical details

EF Core version: 3.0.1
Database provider: Npgsql
Target framework:.NET Core 3.0
Operating system: Windows 10 Pro
IDE: JetBrains Rider

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions