efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Detaching of the parent record changed sub records state to deleted

Open aspirinv opened this issue 7 years ago • 1 comments

Steps to reproduce

  1. Create record with sub collection
  2. Save changes
  3. Detach record from contexxt

Result: Sub records state switched to Deleted

        static void Main(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<Context>()
                .UseInMemoryDatabase(databaseName: "InMemory_db")
                .UseLoggerFactory(LoggerFactory.Create(l => l.AddConsole()));

            DetachSubItemsIssue(optionsBuilder.Options);
        }

        private static void DetachSubItemsIssue(DbContextOptions<Context> options)
        { 
            var post = new Post { Text = "World" };
            var client = new Client { Name = "Richard", Posts = new List<Post> { post } };

            using (var context = new Context(options))
            {
                context.Clients.Add(client);
                context.SaveChanges();

                context.Entry(client).State = EntityState.Detached;
                if (context.Entry(post).State == EntityState.Deleted)
                    throw new Exception("Sub items gets deleted in case of detach of the parent entity");
            }        
        }

The same code works well in EF Core 2.2.6

Further technical details

EF Core version: 3.0.1 Database provider: Microsoft.EntityFrameworkCore.InMemory Target framework: .NET Core 3.0 Operating system: Windows 10 IDE: Visual Studio 2019 16.3

aspirinv avatar Dec 03 '19 10:12 aspirinv

Duplicate of https://github.com/aspnet/EntityFrameworkCore/issues/18982

AndriySvyryd avatar Dec 03 '19 22:12 AndriySvyryd