コード例 #1
0
        public void TestDetachAllTrackedEntities(int numCollection)
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <Chapter06Context>();

            using (var context = new Chapter06Context(options))
            {
                context.Database.EnsureCreated();
                var entityToDetach = context.AddManyTopWithRelationsToDb();
                //ATTEMPT
                using (new TimeThings(_output, $"detach all tracked entities - {numCollection * 3:n0} tracked entities."))
                {
                    foreach (var entityEntry in context.ChangeTracker.Entries()) //#A
                    {
                        if (entityEntry.Entity != null)                          //#B
                        {
                            entityEntry.State = EntityState.Detached;            //#C
                        }
                    }

                    /********************************************
                     #A This will iterate through each tracked EntityEntry in the current DbContext instance
                     #B This filters out tracked entities where the entity class instance has been set to null
                     #C This sets the state of the EntityEntry to Detached
                     **********************************************/
                }

                //VERIFY
                var topEntity = context.Entry(entityToDetach);
                entityToDetach.Collection1.All(x => context.Entry(x).State == EntityState.Detached).ShouldBeTrue();
                entityToDetach.Collection2.All(x => context.Entry(x).State == EntityState.Detached).ShouldBeTrue();
                entityToDetach.Collection3.All(x => context.Entry(x).State == EntityState.Detached).ShouldBeTrue();
            }
        }
        public void TestDetachAllTrackedEntities(int numCollection)
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <Chapter06Context>();

            using (var context = new Chapter06Context(options))
            {
                context.Database.EnsureCreated();
                var entityToDetach = context.AddManyTopWithRelationsToDb();
                //ATTEMPT
                using (new TimeThings(_output, $"detach all tracked entities - {numCollection * 3:n0} tracked entities."))
                {
                    context.ChangeTracker.Clear();
                }

                //VERIFY
                var topEntity = context.Entry(entityToDetach);
                entityToDetach.Collection1.All(x => context.Entry(x).State == EntityState.Detached).ShouldBeTrue();
                entityToDetach.Collection2.All(x => context.Entry(x).State == EntityState.Detached).ShouldBeTrue();
                entityToDetach.Collection3.All(x => context.Entry(x).State == EntityState.Detached).ShouldBeTrue();
            }
        }