コード例 #1
0
 public void Can_get_Context()
 {
     using (var context = new EarlyLearningCenter())
     {
         Assert.Same(context, context.ChangeTracker.Context);
     }
 }
コード例 #2
0
 public void Members_check_arguments()
 {
     using (var context = new EarlyLearningCenter())
     {
         Assert.Equal(
             "entity",
             // ReSharper disable once AssignNullToNotNullAttribute
             Assert.Throws<ArgumentNullException>(() => context.Add<Random>(null)).ParamName);
         Assert.Equal(
             "entity",
             // ReSharper disable once AssignNullToNotNullAttribute
             Assert.ThrowsAsync<ArgumentNullException>(() => context.AddAsync<Random>(null)).Result.ParamName);
         Assert.Equal(
             "entity",
             // ReSharper disable once AssignNullToNotNullAttribute
             Assert.Throws<ArgumentNullException>(
                 () => context.AddAsync<Random>(null, new CancellationToken()).GetAwaiter().GetResult()).ParamName);
         Assert.Equal(
             "entity",
             // ReSharper disable once AssignNullToNotNullAttribute
             Assert.Throws<ArgumentNullException>(() => context.Update<Random>(null)).ParamName);
         Assert.Equal(
             "entity",
             // ReSharper disable once AssignNullToNotNullAttribute
             Assert.ThrowsAsync<ArgumentNullException>(() => context.UpdateAsync<Random>(null)).Result.ParamName);
         Assert.Equal(
             "entity",
             // ReSharper disable once AssignNullToNotNullAttribute
             Assert.ThrowsAsync<ArgumentNullException>(() => context.UpdateAsync<Random>(null, new CancellationToken())).Result.ParamName);
     }
 }
コード例 #3
0
        public void Can_attach_parent_with_child_collection()
        {
            using (var context = new EarlyLearningCenter())
            {
                var category = new Category
                    {
                        Id = 1,
                        Products = new List<Product>
                            {
                                new Product { Id = 1 },
                                new Product { Id = 2 },
                                new Product { Id = 3 }
                            }
                    };

                context.ChangeTracker.TrackGraph(category, e => e.State = EntityState.Modified);

                Assert.Equal(4, context.ChangeTracker.Entries().Count());

                Assert.Equal(EntityState.Modified, context.Entry(category).State);
                Assert.Equal(EntityState.Modified, context.Entry(category.Products[0]).State);
                Assert.Equal(EntityState.Modified, context.Entry(category.Products[1]).State);
                Assert.Equal(EntityState.Modified, context.Entry(category.Products[2]).State);

                Assert.Same(category, category.Products[0].Category);
                Assert.Same(category, category.Products[1].Category);
                Assert.Same(category, category.Products[2].Category);

                Assert.Equal(category.Id, category.Products[0].CategoryId);
                Assert.Equal(category.Id, category.Products[1].CategoryId);
                Assert.Equal(category.Id, category.Products[2].CategoryId);
            }
        }
コード例 #4
0
        public void Can_get_state_manager()
        {
            using (var context = new EarlyLearningCenter())
            {
                var stateManger = context.GetService<IStateManager>();

                Assert.Same(stateManger, context.ChangeTracker.GetInfrastructure());
            }
        }
コード例 #5
0
        public void Can_get_state_manager()
        {
            using (var context = new EarlyLearningCenter())
            {
                var stateManger = ((IAccessor<IServiceProvider>)context).Service.GetRequiredService<IStateManager>();

                Assert.Same(stateManger, ((IAccessor<IStateManager>)context.ChangeTracker).Service);
            }
        }
コード例 #6
0
        public void Can_get_all_entries()
        {
            using (var context = new EarlyLearningCenter())
            {
                var category = context.Add(new Category()).Entity;
                var product = context.Add(new Product()).Entity;

                Assert.Equal(
                    new object[] { category, product },
                    context.ChangeTracker.Entries().Select(e => e.Entity).OrderBy(e => e.GetType().Name));
            }
        }
コード例 #7
0
        public void Each_context_gets_new_scoped_services()
        {
            var serviceProvider = TestHelpers.Instance.CreateServiceProvider();

            IServiceProvider contextServices;
            using (var context = new EarlyLearningCenter(serviceProvider))
            {
                contextServices = ((IInfrastructure<IServiceProvider>)context).Instance;
                Assert.Same(contextServices, ((IInfrastructure<IServiceProvider>)context).Instance);
            }

            using (var context = new EarlyLearningCenter(serviceProvider))
            {
                Assert.NotSame(contextServices, ((IInfrastructure<IServiceProvider>)context).Instance);
            }
        }
コード例 #8
0
        public void Entry_methods_check_arguments()
        {
            var services = new ServiceCollection()
                           .AddScoped <IStateManager, FakeStateManager>();

            var serviceProvider = InMemoryTestHelpers.Instance.CreateServiceProvider(services);

            using var context = new EarlyLearningCenter(serviceProvider);
            Assert.Equal(
                "entity",
                // ReSharper disable once AssignNullToNotNullAttribute
                Assert.Throws <ArgumentNullException>(() => context.Entry(null)).ParamName);
            Assert.Equal(
                "entity",
                // ReSharper disable once AssignNullToNotNullAttribute
                Assert.Throws <ArgumentNullException>(() => context.Entry <Random>(null)).ParamName);
        }
コード例 #9
0
ファイル: DbSetTest.cs プロジェクト: n8hartSA/efcore
        private async Task ChangeStateWithMethod(
            Func <EarlyLearningCenter, Category, Task> action,
            EntityState initialState,
            EntityState expectedState)
        {
            using var context = new EarlyLearningCenter();
            var entity = new Category {
                Id = 1, Name = "Beverages"
            };
            var entry = context.Entry(entity);

            entry.State = initialState;

            await action(context, entity);

            Assert.Equal(expectedState, entry.State);
        }
コード例 #10
0
        public void Can_replace_already_registered_service_with_new_service()
        {
            var factory           = Mock.Of <OriginalValuesFactory>();
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddEntityFramework();
            serviceCollection.AddInstance(factory);

            var provider = serviceCollection.BuildServiceProvider();

            using (var context = new EarlyLearningCenter(provider))
            {
                var configuration = context.Configuration;

                Assert.Same(factory, configuration.Services.OriginalValuesFactory);
            }
        }
コード例 #11
0
ファイル: DbSetTest.cs プロジェクト: zgcodes/EntityFramework
        private static void TrackEntitiesTest(
            Func <DbSet <Category>, Category, EntityEntry <Category> > categoryAdder,
            Func <DbSet <Product>, Product, EntityEntry <Product> > productAdder, EntityState expectedState)
        {
            using (var context = new EarlyLearningCenter())
            {
                var category1 = new Category {
                    Id = 1, Name = "Beverages"
                };
                var category2 = new Category {
                    Id = 2, Name = "Foods"
                };
                var product1 = new Product {
                    Id = 1, Name = "Marmite", Price = 7.99m
                };
                var product2 = new Product {
                    Id = 2, Name = "Bovril", Price = 4.99m
                };

                var categoryEntry1 = categoryAdder(context.Categories, category1);
                var categoryEntry2 = categoryAdder(context.Categories, category2);
                var productEntry1  = productAdder(context.Products, product1);
                var productEntry2  = productAdder(context.Products, product2);

                Assert.Same(category1, categoryEntry1.Entity);
                Assert.Same(category2, categoryEntry2.Entity);
                Assert.Same(product1, productEntry1.Entity);
                Assert.Same(product2, productEntry2.Entity);

                Assert.Same(category1, categoryEntry1.Entity);
                Assert.Equal(expectedState, categoryEntry2.State);
                Assert.Same(category2, categoryEntry2.Entity);
                Assert.Equal(expectedState, categoryEntry2.State);

                Assert.Same(product1, productEntry1.Entity);
                Assert.Equal(expectedState, productEntry1.State);
                Assert.Same(product2, productEntry2.Entity);
                Assert.Equal(expectedState, productEntry2.State);

                Assert.Same(categoryEntry1.GetService(), context.Entry(category1).GetService());
                Assert.Same(categoryEntry2.GetService(), context.Entry(category2).GetService());
                Assert.Same(productEntry1.GetService(), context.Entry(product1).GetService());
                Assert.Same(productEntry2.GetService(), context.Entry(product2).GetService());
            }
        }
コード例 #12
0
ファイル: DbSetTest.cs プロジェクト: AshkanAbd/efcore
        public async Task Use_of_set_throws_if_context_is_disposed()
        {
            DbSet <Category> set;

            using (var context = new EarlyLearningCenter())
            {
                set = context.Categories;
            }

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.Add(new Category())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.Find(77)).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.Attach(new Category())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.Update(new Category())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.Remove(new Category())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.ToList()).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                (await Assert.ThrowsAsync <ObjectDisposedException>(() => set.AddAsync(new Category()).AsTask())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                (await Assert.ThrowsAsync <ObjectDisposedException>(() => set.FindAsync(77).AsTask())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                (await Assert.ThrowsAsync <ObjectDisposedException>(() => set.ToListAsync())).Message);
        }
コード例 #13
0
        public void Can_attach_graph_using_custom_delegate()
        {
            var tracker = new MyTracker(updateExistingEntities: false);

            using (var context = new EarlyLearningCenter())
            {
                var category = new Category
                {
                    Id       = 77,
                    Products = new List <Product>
                    {
                        new Product {
                            Id = 77
                        },
                        new Product {
                            Id = 0
                        },
                        new Product {
                            Id = 78
                        }
                    }
                };

                context.ChangeTracker.TrackGraph(category, tracker.TrackEntity);

                Assert.Equal(4, context.ChangeTracker.Entries().Count());

                Assert.Equal(EntityState.Unchanged, context.Entry(category).State);
                Assert.Equal(EntityState.Unchanged, context.Entry(category.Products[0]).State);
                Assert.Equal(EntityState.Added, context.Entry(category.Products[1]).State);
                Assert.Equal(EntityState.Unchanged, context.Entry(category.Products[2]).State);

                Assert.Equal(77, category.Products[0].Id);
                Assert.Equal(777, category.Products[1].Id);
                Assert.Equal(78, category.Products[2].Id);

                Assert.Same(category, category.Products[0].Category);
                Assert.Same(category, category.Products[1].Category);
                Assert.Same(category, category.Products[2].Category);

                Assert.Equal(category.Id, category.Products[0].CategoryId);
                Assert.Equal(category.Id, category.Products[1].CategoryId);
                Assert.Equal(category.Id, category.Products[2].CategoryId);
            }
        }
コード例 #14
0
        private static void KeyValueAttachTest(Action <Category, ChangeTracker> tracker, bool expectModified = false)
        {
            using (var context = new EarlyLearningCenter())
            {
                var category = new Category
                {
                    Id       = 77,
                    Products = new List <Product>
                    {
                        new Product {
                            Id = 77
                        },
                        new Product {
                            Id = 0
                        },
                        new Product {
                            Id = 78
                        }
                    }
                };

                tracker(category, context.ChangeTracker);

                Assert.Equal(4, context.ChangeTracker.Entries().Count());

                var nonAddedState = expectModified ? EntityState.Modified : EntityState.Unchanged;

                Assert.Equal(nonAddedState, context.Entry(category).State);
                Assert.Equal(nonAddedState, context.Entry(category.Products[0]).State);
                Assert.Equal(EntityState.Added, context.Entry(category.Products[1]).State);
                Assert.Equal(nonAddedState, context.Entry(category.Products[2]).State);

                Assert.Equal(77, category.Products[0].Id);
                Assert.Equal(1, category.Products[1].Id);
                Assert.Equal(78, category.Products[2].Id);

                Assert.Same(category, category.Products[0].Category);
                Assert.Same(category, category.Products[1].Category);
                Assert.Same(category, category.Products[2].Category);

                Assert.Equal(category.Id, category.Products[0].CategoryId);
                Assert.Equal(category.Id, category.Products[1].CategoryId);
                Assert.Equal(category.Id, category.Products[2].CategoryId);
            }
        }
コード例 #15
0
ファイル: DbSetTest.cs プロジェクト: AshkanAbd/efcore
        public async Task Use_of_set_throws_if_obtained_from_disposed_context()
        {
            var context = new EarlyLearningCenter();

            context.Dispose();

            var set = context.Categories;

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.Add(new Category())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.Find(77)).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.Attach(new Category())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.Update(new Category())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.Remove(new Category())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => set.ToList()).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                (await Assert.ThrowsAsync <ObjectDisposedException>(() => set.AddAsync(new Category()).AsTask())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                (await Assert.ThrowsAsync <ObjectDisposedException>(() => set.FindAsync(77).AsTask())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                (await Assert.ThrowsAsync <ObjectDisposedException>(() => set.ToListAsync())).Message);
        }
コード例 #16
0
        private static async Task TrackMultipleEntitiesTestEnumerable(
            Func <EarlyLearningCenter, IEnumerable <Category>, Task> categoryAdder,
            Func <EarlyLearningCenter, IEnumerable <Product>, Task> productAdder, EntityState expectedState)
        {
            using (var context = new EarlyLearningCenter())
            {
                var category1 = new Category {
                    Id = 1, Name = "Beverages"
                };
                var category2 = new Category {
                    Id = 2, Name = "Foods"
                };
                var product1 = new Product {
                    Id = 1, Name = "Marmite", Price = 7.99m
                };
                var product2 = new Product {
                    Id = 2, Name = "Bovril", Price = 4.99m
                };

                await categoryAdder(
                    context, new List <Category> {
                    category1, category2
                });
                await productAdder(
                    context, new List <Product> {
                    product1, product2
                });

                Assert.Same(category1, context.Entry(category1).Entity);
                Assert.Same(category2, context.Entry(category2).Entity);
                Assert.Same(product1, context.Entry(product1).Entity);
                Assert.Same(product2, context.Entry(product2).Entity);

                Assert.Same(category1, context.Entry(category1).Entity);
                Assert.Equal(expectedState, context.Entry(category1).State);
                Assert.Same(category2, context.Entry(category2).Entity);
                Assert.Equal(expectedState, context.Entry(category2).State);

                Assert.Same(product1, context.Entry(product1).Entity);
                Assert.Equal(expectedState, context.Entry(product1).State);
                Assert.Same(product2, context.Entry(product2).Entity);
                Assert.Equal(expectedState, context.Entry(product2).State);
            }
        }
コード例 #17
0
        public void Explicitly_calling_DetectChanges_works_even_if_auto_DetectChanges_is_switched_off()
        {
            using (var context = new EarlyLearningCenter())
            {
                context.ChangeTracker.AutoDetectChangesEnabled = false;

                var entry = context.Attach(new Product {
                    Id = 1, CategoryId = 66
                });

                entry.Entity.CategoryId = 77;

                Assert.Equal(EntityState.Unchanged, entry.State);

                context.ChangeTracker.DetectChanges();

                Assert.Equal(EntityState.Modified, entry.State);
            }
        }
コード例 #18
0
        public void TrackGraph_does_not_call_DetectChanges()
        {
            var provider = TestHelpers.Instance.CreateServiceProvider(new ServiceCollection().AddScoped <IChangeDetector, ChangeDetectorProxy>());

            using (var context = new EarlyLearningCenter(provider))
            {
                var changeDetector = (ChangeDetectorProxy)context.GetService <IChangeDetector>();

                changeDetector.DetectChangesCalled = false;

                context.ChangeTracker.TrackGraph(CreateSimpleGraph(2), e => e.State = EntityState.Unchanged);

                Assert.False(changeDetector.DetectChangesCalled);

                context.ChangeTracker.DetectChanges();

                Assert.True(changeDetector.DetectChangesCalled);
            }
        }
コード例 #19
0
        private static void TrackMultipleEntitiesTest(
            Func <DbSet <Category>, Category[], IReadOnlyList <EntityEntry <Category> > > categoryAdder,
            Func <DbSet <Product>, Product[], IReadOnlyList <EntityEntry <Product> > > productAdder, EntityState expectedState)
        {
            using (var context = new EarlyLearningCenter())
            {
                var category1 = new Category {
                    Id = 1, Name = "Beverages"
                };
                var category2 = new Category {
                    Id = 2, Name = "Foods"
                };
                var product1 = new Product {
                    Id = 1, Name = "Marmite", Price = 7.99m
                };
                var product2 = new Product {
                    Id = 2, Name = "Bovril", Price = 4.99m
                };

                var categoryEntries = categoryAdder(context.Categories, new[] { category1, category2 });
                var productEntries  = productAdder(context.Products, new[] { product1, product2 });

                Assert.Same(category1, categoryEntries[0].Entity);
                Assert.Same(category2, categoryEntries[1].Entity);
                Assert.Same(product1, productEntries[0].Entity);
                Assert.Same(product2, productEntries[1].Entity);

                Assert.Same(category1, categoryEntries[0].Entity);
                Assert.Equal(expectedState, categoryEntries[0].State);
                Assert.Same(category2, categoryEntries[1].Entity);
                Assert.Equal(expectedState, categoryEntries[1].State);

                Assert.Same(product1, productEntries[0].Entity);
                Assert.Equal(expectedState, productEntries[0].State);
                Assert.Same(product2, productEntries[1].Entity);
                Assert.Equal(expectedState, productEntries[1].State);

                Assert.Same(categoryEntries[0].StateEntry, context.Entry(category1).StateEntry);
                Assert.Same(categoryEntries[1].StateEntry, context.Entry(category2).StateEntry);
                Assert.Same(productEntries[0].StateEntry, context.Entry(product1).StateEntry);
                Assert.Same(productEntries[1].StateEntry, context.Entry(product2).StateEntry);
            }
        }
コード例 #20
0
        public void Can_set_known_singleton_services_using_instance_sugar()
        {
            var collectionSource   = Mock.Of <ClrCollectionAccessorSource>();
            var getterSource       = Mock.Of <ClrPropertyGetterSource>();
            var setterSource       = Mock.Of <ClrPropertySetterSource>();
            var keyFactorySource   = Mock.Of <EntityKeyFactorySource>();
            var materializerSource = Mock.Of <EntityMaterializerSource>();
            var setFinder          = Mock.Of <DbSetFinder>();
            var setInitializer     = Mock.Of <DbSetInitializer>();
            var loggerFactory      = Mock.Of <ILoggerFactory>();
            var modelSource        = Mock.Of <IModelSource>();

            var services = new ServiceCollection();

            services.AddEntityFramework()
            .UseClrCollectionAccessorSource(collectionSource)
            .UseClrPropertyGetterSource(getterSource)
            .UseClrPropertySetterSource(setterSource)
            .UseEntityKeyFactorySource(keyFactorySource)
            .UseEntityMaterializerSource(materializerSource)
            .UseDbSetFinder(setFinder)
            .UseDbSetInitializer(setInitializer)
            .UseLoggerFactory(loggerFactory)
            .UseModelSource(modelSource);

            var provider = services.BuildServiceProvider();

            using (var context = new EarlyLearningCenter(provider))
            {
                var configuration = context.Configuration;

                Assert.Same(collectionSource, configuration.Services.ServiceProvider.GetService <ClrCollectionAccessorSource>());
                Assert.Same(getterSource, configuration.Services.ClrPropertyGetterSource);
                Assert.Same(setterSource, configuration.Services.ClrPropertySetterSource);
                Assert.Same(keyFactorySource, configuration.Services.EntityKeyFactorySource);
                Assert.Same(materializerSource, configuration.Services.ServiceProvider.GetService <EntityMaterializerSource>());
                Assert.Same(setFinder, configuration.Services.ServiceProvider.GetService <DbSetFinder>());
                Assert.Same(setInitializer, configuration.Services.ServiceProvider.GetService <DbSetInitializer>());
                Assert.Same(loggerFactory, configuration.Services.ServiceProvider.GetService <ILoggerFactory>());
                Assert.Same(modelSource, configuration.Services.ModelSource);
            }
        }
コード例 #21
0
        public void Can_get_all_entities_for_an_entity_of_a_given_type()
        {
            using (var context = new EarlyLearningCenter())
            {
                var category = context.Add(new Category()).Entity;
                var product  = context.Add(new Product()).Entity;

                Assert.Equal(
                    new object[] { product },
                    context.ChangeTracker.Entries <Product>().Select(e => e.Entity).OrderBy(e => e.GetType().Name));

                Assert.Equal(
                    new object[] { category },
                    context.ChangeTracker.Entries <Category>().Select(e => e.Entity).OrderBy(e => e.GetType().Name));

                Assert.Equal(
                    new object[] { category, product },
                    context.ChangeTracker.Entries <object>().Select(e => e.Entity).OrderBy(e => e.GetType().Name));
            }
        }
コード例 #22
0
ファイル: DbSetTest.cs プロジェクト: n8hartSA/efcore
        public void Using_shared_type_entity_type_db_set_with_incorrect_return_type_throws()
        {
            using var context = new EarlyLearningCenter();

            var dbSet = context.Set <Dictionary <string, object> >("SharedEntity");

            Assert.NotNull(dbSet.Add(new Dictionary <string, object> {
                { "Id", 1 }
            }));
            Assert.NotNull(dbSet.ToList());

            var wrongDbSet = context.Set <Category>("SharedEntity");

            Assert.Equal(
                CoreStrings.DbSetIncorrectGenericType("SharedEntity", "Dictionary<string, object>", "Category"),
                Assert.Throws <InvalidOperationException>(() => wrongDbSet.Add(new Category())).Message);
            Assert.Equal(
                CoreStrings.DbSetIncorrectGenericType("SharedEntity", "Dictionary<string, object>", "Category"),
                Assert.Throws <InvalidOperationException>(() => wrongDbSet.ToList()).Message);
        }
コード例 #23
0
        private static void TrackEntitiesTest(
            Func <DbContext, Category, Category> categoryAdder,
            Func <DbContext, Product, Product> productAdder, EntityState expectedState)
        {
            using (var context = new EarlyLearningCenter())
            {
                var category1 = new Category {
                    Id = 1, Name = "Beverages"
                };
                var category2 = new Category {
                    Id = 2, Name = "Foods"
                };
                var product1 = new Product {
                    Id = 1, Name = "Marmite", Price = 7.99m
                };
                var product2 = new Product {
                    Id = 2, Name = "Bovril", Price = 4.99m
                };

                Assert.Same(category1, categoryAdder(context, category1));
                Assert.Same(category2, categoryAdder(context, category2));
                Assert.Same(product1, productAdder(context, product1));
                Assert.Same(product2, productAdder(context, product2));

                var categoryEntry = context.ChangeTracker.Entry(category1);
                Assert.Same(category1, categoryEntry.Entity);
                Assert.Equal(expectedState, categoryEntry.State);

                categoryEntry = context.ChangeTracker.Entry(category2);
                Assert.Same(category2, categoryEntry.Entity);
                Assert.Equal(expectedState, categoryEntry.State);

                var productEntry = context.ChangeTracker.Entry(product1);
                Assert.Same(product1, productEntry.Entity);
                Assert.Equal(expectedState, productEntry.State);

                productEntry = context.ChangeTracker.Entry(product2);
                Assert.Same(product2, productEntry.Entity);
                Assert.Equal(expectedState, productEntry.State);
            }
        }
コード例 #24
0
        public void Entities_that_are_already_tracked_will_not_get_attached()
        {
            using (var context = new EarlyLearningCenter())
            {
                var existingProduct = context.Attach(new Product {
                    Id = 2, CategoryId = 1
                }).Entity;

                var category = new Category
                {
                    Id       = 1,
                    Products = new List <Product>
                    {
                        new Product {
                            Id = 1
                        },
                        existingProduct,
                        new Product {
                            Id = 3
                        }
                    }
                };

                context.ChangeTracker.TrackGraph(category, e => e.State = EntityState.Modified);

                Assert.Equal(4, context.ChangeTracker.Entries().Count());

                Assert.Equal(EntityState.Modified, context.Entry(category).State);
                Assert.Equal(EntityState.Modified, context.Entry(category.Products[0]).State);
                Assert.Equal(EntityState.Unchanged, context.Entry(category.Products[1]).State);
                Assert.Equal(EntityState.Modified, context.Entry(category.Products[2]).State);

                Assert.Same(category, category.Products[0].Category);
                Assert.Same(category, category.Products[1].Category);
                Assert.Same(category, category.Products[2].Category);

                Assert.Equal(category.Id, category.Products[0].CategoryId);
                Assert.Equal(category.Id, category.Products[1].CategoryId);
                Assert.Equal(category.Id, category.Products[2].CategoryId);
            }
        }
コード例 #25
0
        public void Can_attach_child_with_reference_to_parent()
        {
            using (var context = new EarlyLearningCenter())
            {
                var product = new Product {
                    Id = 1, Category = new Category {
                        Id = 1
                    }
                };

                context.ChangeTracker.TrackGraph(product, e => e.State = EntityState.Modified);

                Assert.Equal(2, context.ChangeTracker.Entries().Count());

                Assert.Equal(EntityState.Modified, context.Entry(product).State);
                Assert.Equal(EntityState.Modified, context.Entry(product.Category).State);

                Assert.Same(product, product.Category.Products[0]);
                Assert.Equal(product.Category.Id, product.CategoryId);
            }
        }
コード例 #26
0
        public void SaveChanges_doesnt_call_DataStore_when_nothing_is_dirty()
        {
            var store = new Mock <DataStore>();

            var servicesMock = new Mock <DataStoreServices>();

            servicesMock.Setup(m => m.Store).Returns(store.Object);
            servicesMock.Setup(m => m.ModelBuilderFactory).Returns(new ModelBuilderFactory());

            var sourceMock = new Mock <DataStoreSource>();

            sourceMock.Setup(m => m.IsAvailable).Returns(true);
            sourceMock.Setup(m => m.IsConfigured).Returns(true);
            sourceMock.Setup(m => m.StoreServices).Returns(servicesMock.Object);

            var services = new ServiceCollection();

            services.AddEntityFramework();
            services.AddInstance(sourceMock.Object);
            var serviceProvider = services.BuildServiceProvider();

            var options = new DbContextOptions();

            using (var context = new EarlyLearningCenter(serviceProvider, options))
            {
                context.ChangeTracker.Entry(new Category {
                    Id = 1
                }).State = EntityState.Unchanged;
                context.ChangeTracker.Entry(new Category {
                    Id = 2
                }).State = EntityState.Unchanged;
                Assert.Equal(2, context.ChangeTracker.Entries().Count());

                context.SaveChanges();
            }

            store.Verify(
                s => s.SaveChangesAsync(It.IsAny <IReadOnlyList <StateEntry> >(), It.IsAny <CancellationToken>()),
                Times.Never);
        }
コード例 #27
0
        public void Can_attach_parent_with_child_collection()
        {
            using (var context = new EarlyLearningCenter())
            {
                var category = new Category
                {
                    Id       = 1,
                    Products = new List <Product>
                    {
                        new Product {
                            Id = 1
                        },
                        new Product {
                            Id = 2
                        },
                        new Product {
                            Id = 3
                        }
                    }
                };

                context.ChangeTracker.TrackGraph(category, e => e.State = EntityState.Modified);

                Assert.Equal(4, context.ChangeTracker.Entries().Count());

                Assert.Equal(EntityState.Modified, context.Entry(category).State);
                Assert.Equal(EntityState.Modified, context.Entry(category.Products[0]).State);
                Assert.Equal(EntityState.Modified, context.Entry(category.Products[1]).State);
                Assert.Equal(EntityState.Modified, context.Entry(category.Products[2]).State);

                Assert.Same(category, category.Products[0].Category);
                Assert.Same(category, category.Products[1].Category);
                Assert.Same(category, category.Products[2].Category);

                Assert.Equal(category.Id, category.Products[0].CategoryId);
                Assert.Equal(category.Id, category.Products[1].CategoryId);
                Assert.Equal(category.Id, category.Products[2].CategoryId);
            }
        }
コード例 #28
0
ファイル: DbSetTest.cs プロジェクト: n8hartSA/efcore
        public async Task Can_add_new_entities_to_context_with_key_generation(bool async)
        {
            using var context = new EarlyLearningCenter();
            var gu1 = new TheGu {
                ShirtColor = "Red"
            };
            var gu2 = new TheGu {
                ShirtColor = "Still Red"
            };

            if (async)
            {
                Assert.Same(gu1, (await context.Gus.AddAsync(gu1)).Entity);
                Assert.Same(gu2, (await context.Gus.AddAsync(gu2)).Entity);
            }
            else
            {
                Assert.Same(gu1, context.Gus.Add(gu1).Entity);
                Assert.Same(gu2, context.Gus.Add(gu2).Entity);
            }

            Assert.NotEqual(default, gu1.Id);
コード例 #29
0
ファイル: DbSetTest.cs プロジェクト: zgcodes/EntityFramework
        private static void TrackMultipleEntitiesTest(
            Action <EarlyLearningCenter, Category[]> categoryAdder,
            Action <EarlyLearningCenter, Product[]> productAdder, EntityState expectedState)
        {
            using (var context = new EarlyLearningCenter())
            {
                var category1 = new Category {
                    Id = 1, Name = "Beverages"
                };
                var category2 = new Category {
                    Id = 2, Name = "Foods"
                };
                var product1 = new Product {
                    Id = 1, Name = "Marmite", Price = 7.99m
                };
                var product2 = new Product {
                    Id = 2, Name = "Bovril", Price = 4.99m
                };

                categoryAdder(context, new[] { category1, category2 });
                productAdder(context, new[] { product1, product2 });

                Assert.Same(category1, context.Entry(category1).Entity);
                Assert.Same(category2, context.Entry(category2).Entity);
                Assert.Same(product1, context.Entry(product1).Entity);
                Assert.Same(product2, context.Entry(product2).Entity);

                Assert.Same(category1, context.Entry(category1).Entity);
                Assert.Equal(expectedState, context.Entry(category1).State);
                Assert.Same(category2, context.Entry(category2).Entity);
                Assert.Equal(expectedState, context.Entry(category2).State);

                Assert.Same(product1, context.Entry(product1).Entity);
                Assert.Equal(expectedState, context.Entry(product1).State);
                Assert.Same(product2, context.Entry(product2).Entity);
                Assert.Equal(expectedState, context.Entry(product2).State);
            }
        }
コード例 #30
0
        public void Can_set_known_singleton_services_using_type_activation()
        {
            var services = new ServiceCollection();

            services.AddEntityFramework()
            .UseActiveIdentityGenerators <FakeActiveIdentityGenerators>()
            .UseClrCollectionAccessorSource <FakeClrCollectionAccessorSource>()
            .UseClrPropertyGetterSource <FakeClrPropertyGetterSource>()
            .UseClrPropertySetterSource <FakeClrPropertySetterSource>()
            .UseEntityKeyFactorySource <FakeEntityKeyFactorySource>()
            .UseEntityMaterializerSource <FakeEntityMaterializerSource>()
            .UseDbSetFinder <FakeDbSetFinder>()
            .UseDbSetInitializer <FakeDbSetInitializer>()
            .UseEntityStateListener <FakeEntityStateListener>()
            .UseIdentityGeneratorFactory <FakeIdentityGeneratorFactory>()
            .UseContextSets <FakeContextSets>()
            .UseLoggerFactory <FakeLoggerFactory>()
            .UseModelSource <FakeModelSource>();

            var provider = services.BuildServiceProvider();

            using (var context = new EarlyLearningCenter(provider))
            {
                var configuration = context.Configuration;

                Assert.IsType <FakeActiveIdentityGenerators>(configuration.Services.ActiveIdentityGenerators);
                Assert.IsType <FakeClrCollectionAccessorSource>(configuration.Services.ServiceProvider.GetService <ClrCollectionAccessorSource>());
                Assert.IsType <FakeClrPropertyGetterSource>(configuration.Services.ClrPropertyGetterSource);
                Assert.IsType <FakeClrPropertySetterSource>(configuration.Services.ClrPropertySetterSource);
                Assert.IsType <FakeEntityKeyFactorySource>(configuration.Services.EntityKeyFactorySource);
                Assert.IsType <FakeEntityMaterializerSource>(configuration.Services.ServiceProvider.GetService <EntityMaterializerSource>());
                Assert.IsType <FakeDbSetFinder>(configuration.Services.ServiceProvider.GetService <DbSetFinder>());
                Assert.IsType <FakeDbSetInitializer>(configuration.Services.ServiceProvider.GetService <DbSetInitializer>());
                Assert.IsType <FakeIdentityGeneratorFactory>(configuration.Services.ServiceProvider.GetService <IdentityGeneratorFactory>());
                Assert.IsType <FakeLoggerFactory>(configuration.Services.ServiceProvider.GetService <ILoggerFactory>());
                Assert.IsType <FakeModelSource>(configuration.Services.ModelSource);
            }
        }
コード例 #31
0
        [Fact] // Issue #1207
        public void Can_add_identifying_dependents_and_principal_starting_in_the_middle_with_key_generation()
        {
            using (var context = new EarlyLearningCenter())
            {
                var tagDetails1 = new ProductDetailsTagDetails
                {
                    Tag = new ProductDetailsTag
                    {
                        Details = new ProductDetails
                        {
                            Product = new Product()
                        }
                    }
                };

                var tagDetails2 = new ProductDetailsTagDetails
                {
                    Tag = new ProductDetailsTag
                    {
                        Details = new ProductDetails
                        {
                            Product = new Product()
                        }
                    }
                };

                context.Add(tagDetails1.Tag);
                context.Add(tagDetails2.Tag);
                context.Add(tagDetails1);
                context.Add(tagDetails2);
                context.Add(tagDetails2.Tag.Details);
                context.Add(tagDetails1.Tag.Details);
                context.Add(tagDetails1.Tag.Details.Product);
                context.Add(tagDetails2.Tag.Details.Product);

                AssertProductAndDetailsFixedUp(context, tagDetails1, tagDetails2);
            }
        }
コード例 #32
0
ファイル: DbSetTest.cs プロジェクト: ChuYuzhi/EntityFramework
        private static void TrackEntitiesTest(
            Func<DbSet<Category>, Category, EntityEntry<Category>> categoryAdder,
            Func<DbSet<Product>, Product, EntityEntry<Product>> productAdder, EntityState expectedState)
        {
            using (var context = new EarlyLearningCenter())
            {
                var category1 = new Category { Id = 1, Name = "Beverages" };
                var category2 = new Category { Id = 2, Name = "Foods" };
                var product1 = new Product { Id = 1, Name = "Marmite", Price = 7.99m };
                var product2 = new Product { Id = 2, Name = "Bovril", Price = 4.99m };

                var categoryEntry1 = categoryAdder(context.Categories, category1);
                var categoryEntry2 = categoryAdder(context.Categories, category2);
                var productEntry1 = productAdder(context.Products, product1);
                var productEntry2 = productAdder(context.Products, product2);

                Assert.Same(category1, categoryEntry1.Entity);
                Assert.Same(category2, categoryEntry2.Entity);
                Assert.Same(product1, productEntry1.Entity);
                Assert.Same(product2, productEntry2.Entity);

                Assert.Same(category1, categoryEntry1.Entity);
                Assert.Equal(expectedState, categoryEntry2.State);
                Assert.Same(category2, categoryEntry2.Entity);
                Assert.Equal(expectedState, categoryEntry2.State);

                Assert.Same(product1, productEntry1.Entity);
                Assert.Equal(expectedState, productEntry1.State);
                Assert.Same(product2, productEntry2.Entity);
                Assert.Equal(expectedState, productEntry2.State);

                Assert.Same(categoryEntry1.GetInfrastructure(), context.Entry(category1).GetInfrastructure());
                Assert.Same(categoryEntry2.GetInfrastructure(), context.Entry(category2).GetInfrastructure());
                Assert.Same(productEntry1.GetInfrastructure(), context.Entry(product1).GetInfrastructure());
                Assert.Same(productEntry2.GetInfrastructure(), context.Entry(product2).GetInfrastructure());
            }
        }
コード例 #33
0
        [Fact] // Issue #1207
        public void Can_add_principal_and_identifying_dependents_starting_in_the_middle_with_key_generation()
        {
            using (var context = new EarlyLearningCenter())
            {
                var product1 = new Product
                {
                    Details = new ProductDetails
                    {
                        Tag = new ProductDetailsTag
                        {
                            TagDetails = new ProductDetailsTagDetails()
                        }
                    }
                };
                var product2 = new Product
                {
                    Details = new ProductDetails
                    {
                        Tag = new ProductDetailsTag
                        {
                            TagDetails = new ProductDetailsTagDetails()
                        }
                    }
                };

                context.Add(product1.Details);
                context.Add(product2.Details);
                context.Add(product1.Details.Tag.TagDetails);
                context.Add(product1);
                context.Add(product1.Details.Tag);
                context.Add(product2.Details.Tag);
                context.Add(product2.Details.Tag.TagDetails);
                context.Add(product2);

                AssertProductAndDetailsFixedUp(context, product1.Details.Tag.TagDetails, product2.Details.Tag.TagDetails);
            }
        }
コード例 #34
0
        public void Entries_calls_DetectChanges_by_default(bool useGenericOverload)
        {
            using (var context = new EarlyLearningCenter())
            {
                var entry = context.Attach(new Product {
                    Id = 1, CategoryId = 66
                });

                entry.Entity.CategoryId = 77;

                Assert.Equal(EntityState.Unchanged, entry.State);

                if (useGenericOverload)
                {
                    context.ChangeTracker.Entries <Product>();
                }
                else
                {
                    context.ChangeTracker.Entries();
                }

                Assert.Equal(EntityState.Modified, entry.State);
            }
        }
コード例 #35
0
        [Fact] // Issue #1207
        public void Can_add_identifying_dependents_and_principal_with_reverse_post_nav_fixup_with_key_generation()
        {
            using (var context = new EarlyLearningCenter())
            {
                var product1    = new Product();
                var details1    = new ProductDetails();
                var tag1        = new ProductDetailsTag();
                var tagDetails1 = new ProductDetailsTagDetails();

                var product2    = new Product();
                var details2    = new ProductDetails();
                var tag2        = new ProductDetailsTag();
                var tagDetails2 = new ProductDetailsTagDetails();

                context.Add(product1);
                context.Add(tagDetails2);
                context.Add(details1);
                context.Add(tag2);
                context.Add(details2);
                context.Add(tag1);
                context.Add(tagDetails1);
                context.Add(product2);

                tagDetails1.Tag  = tag1;
                tag1.Details     = details1;
                details1.Product = product1;

                tagDetails2.Tag  = tag2;
                tag2.Details     = details2;
                details2.Product = product2;

                context.ChangeTracker.DetectChanges();

                AssertProductAndDetailsFixedUp(context, product1.Details.Tag.TagDetails, product2.Details.Tag.TagDetails);
            }
        }
コード例 #36
0
        public void Can_attach_child_with_one_to_one_parents()
        {
            using (var context = new EarlyLearningCenter())
            {
                var tag = new ProductDetailsTag {
                    Id = 1, Details = new ProductDetails {
                        Id = 1, Product = new Product {
                            Id = 1
                        }
                    }
                };

                context.ChangeTracker.AttachGraph(tag, e => e.SetState(EntityState.Unchanged));

                Assert.Equal(3, context.ChangeTracker.Entries().Count());

                Assert.Equal(EntityState.Unchanged, context.Entry(tag).State);
                Assert.Equal(EntityState.Unchanged, context.Entry(tag.Details).State);
                Assert.Equal(EntityState.Unchanged, context.Entry(tag.Details.Product).State);

                Assert.Same(tag, tag.Details.Tag);
                Assert.Same(tag.Details, tag.Details.Product.Details);
            }
        }
コード例 #37
0
        public void Can_attach_entity_with_one_to_one_parent_and_child()
        {
            using (var context = new EarlyLearningCenter())
            {
                var details = new ProductDetails {
                    Id = 1, Product = new Product {
                        Id = 1
                    }, Tag = new ProductDetailsTag {
                        Id = 1
                    }
                };

                context.ChangeTracker.TrackGraph(details, e => e.State = EntityState.Unchanged);

                Assert.Equal(3, context.ChangeTracker.Entries().Count());

                Assert.Equal(EntityState.Unchanged, context.Entry(details).State);
                Assert.Equal(EntityState.Unchanged, context.Entry(details.Product).State);
                Assert.Equal(EntityState.Unchanged, context.Entry(details.Tag).State);

                Assert.Same(details, details.Tag.Details);
                Assert.Same(details, details.Product.Details);
            }
        }
コード例 #38
0
        [Fact] // Issue #1246
        public void Can_attach_with_inconsistent_FK_dependent_first_reference_not_fixed_up()
        {
            using (var context = new EarlyLearningCenter(TestHelpers.Instance.CreateServiceProvider()))
            {
                var category = new Category { Id = 1, Name = "Beverages" };
                var product = new Product { Id = 1, CategoryId = 7, Name = "Marmite" };
                category.Products = new List<Product> { product };

                context.Attach(product, behavior: GraphBehavior.SingleObject);

                Assert.Equal(7, product.CategoryId);
                Assert.Same(product, category.Products.Single());
                Assert.Null(product.Category);
                Assert.Equal(EntityState.Detached, context.Entry(category).State);
                Assert.Equal(EntityState.Unchanged, context.Entry(product).State);

                context.Attach(category, behavior: GraphBehavior.SingleObject);

                Assert.Equal(7, product.CategoryId);
                Assert.Same(product, category.Products.Single());
                Assert.Null(product.Category);
                Assert.Equal(EntityState.Unchanged, context.Entry(category).State);
                Assert.Equal(EntityState.Unchanged, context.Entry(product).State);
            }
        }
コード例 #39
0
        public void It_throws_with_derived_name()
        {
            var context = new EarlyLearningCenter();

            context.Dispose();

            var ex = Assert.Throws<ObjectDisposedException>(() => context.Model);
            Assert.Contains(nameof(EarlyLearningCenter), ex.Message);
        }
コード例 #40
0
        public void Entry_methods_delegate_to_underlying_state_manager()
        {
            var entity = new Random();
            var stateManagerMock = new Mock<IStateManager>();
            var entry = CreateInternalEntryMock().Object;
            stateManagerMock.Setup(m => m.GetOrCreateEntry(entity)).Returns(entry);

            var services = new ServiceCollection()
                .AddScoped(_ => stateManagerMock.Object);

            var serviceProvider = TestHelpers.Instance.CreateServiceProvider(services);

            using (var context = new EarlyLearningCenter(serviceProvider))
            {
                Assert.Same(entry, context.Entry(entity).GetInfrastructure());
                Assert.Same(entry, context.Entry((object)entity).GetInfrastructure());
            }
        }
コード例 #41
0
        public void Can_get_replaced_singleton_service_from_scoped_configuration()
        {
            var provider = new ServiceCollection()
                .AddEntityFramework()
                .GetInfrastructure()
                .AddSingleton<IEntityMaterializerSource, FakeEntityMaterializerSource>()
                .BuildServiceProvider();

            using (var context = new EarlyLearningCenter(provider))
            {
                Assert.IsType<FakeEntityMaterializerSource>(context.GetService<IEntityMaterializerSource>());
            }
        }
コード例 #42
0
        public void Replaced_services_are_scoped_appropriately()
        {
            var services = new ServiceCollection();
            services
                .AddEntityFramework()
                .GetInfrastructure()
                .AddSingleton<IModelSource, FakeModelSource>()
                .AddScoped<IStateManager, FakeStateManager>();

            var provider = services.BuildServiceProvider();

            var context = new EarlyLearningCenter(provider);

            var modelSource = context.GetService<IModelSource>();

            context.Dispose();

            context = new EarlyLearningCenter(provider);

            var stateManager = context.GetService<IStateManager>();

            Assert.Same(stateManager, context.GetService<IStateManager>());

            Assert.Same(modelSource, context.GetService<IModelSource>());

            context.Dispose();

            context = new EarlyLearningCenter(provider);

            Assert.NotSame(stateManager, context.GetService<IStateManager>());

            Assert.Same(modelSource, context.GetService<IModelSource>());

            context.Dispose();
        }
コード例 #43
0
        public void Can_set_known_context_scoped_services_using_type_activation()
        {
            var services = new ServiceCollection()
                .AddScoped<IStateManager, FakeStateManager>();

            var provider = TestHelpers.Instance.CreateServiceProvider(services);

            using (var context = new EarlyLearningCenter(provider))
            {
                Assert.IsType<FakeStateManager>(context.GetService<IStateManager>());
            }
        }
コード例 #44
0
        public void Can_set_known_singleton_services_using_type_activation()
        {
            var services = new ServiceCollection()
                .AddSingleton<IModelSource, FakeModelSource>();

            var provider = TestHelpers.Instance.CreateServiceProvider(services);

            using (var context = new EarlyLearningCenter(provider))
            {
                Assert.IsType<FakeModelSource>(context.GetService<IModelSource>());
            }
        }
コード例 #45
0
        public void Can_set_known_singleton_services_using_instance_sugar()
        {
            var modelSource = Mock.Of<IModelSource>();

            var services = new ServiceCollection()
                .AddInstance(modelSource);

            var provider = TestHelpers.Instance.CreateServiceProvider(services);

            using (var context = new EarlyLearningCenter(provider))
            {
                Assert.Same(modelSource, context.GetService<IModelSource>());
            }
        }
コード例 #46
0
        public void Can_replace_already_registered_service_with_new_service()
        {
            var factory = Mock.Of<IOriginalValuesFactory>();
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddEntityFramework();
            serviceCollection.AddInstance(factory);

            var provider = serviceCollection.BuildServiceProvider();

            using (var context = new EarlyLearningCenter(provider))
            {
                Assert.Same(factory, context.GetService<IOriginalValuesFactory>());
            }
        }
コード例 #47
0
        public void Can_start_with_custom_services_by_passing_in_base_service_provider()
        {
            var factory = Mock.Of<IOriginalValuesFactory>();
            var serviceCollection = new ServiceCollection()
                .AddSingleton<IDbSetFinder, DbSetFinder>()
                .AddSingleton<IDbSetSource, DbSetSource>()
                .AddSingleton<IEntityMaterializerSource, EntityMaterializerSource>()
                .AddSingleton<IMemberMapper, MemberMapper>()
                .AddSingleton<IFieldMatcher, FieldMatcher>()
                .AddSingleton<DatabaseProviderSelector>()
                .AddScoped<IDbSetInitializer, DbSetInitializer>()
                .AddScoped<IDbContextServices, DbContextServices>()
                .AddLogging()
                .AddInstance(factory);

            var provider = serviceCollection.BuildServiceProvider();

            using (var context = new EarlyLearningCenter(provider))
            {
                Assert.Same(factory, context.GetService<IOriginalValuesFactory>());
            }
        }
コード例 #48
0
 public void Can_get_singleton_service_from_scoped_configuration()
 {
     using (var context = new EarlyLearningCenter())
     {
         Assert.IsType<StateManager>(context.GetService<IStateManager>());
     }
 }
コード例 #49
0
 public void Default_context_scoped_services_are_registered_when_parameterless_constructor_used()
 {
     using (var context = new EarlyLearningCenter())
     {
         Assert.IsType<InternalEntityEntryFactory>(context.GetService<IInternalEntityEntryFactory>());
     }
 }
コード例 #50
0
 private static void TrackNoEntitiesTest(Action<DbContext> categoryAdder, Action<DbContext> productAdder)
 {
     using (var context = new EarlyLearningCenter(TestHelpers.Instance.CreateServiceProvider()))
     {
         categoryAdder(context);
         productAdder(context);
         Assert.Empty(context.ChangeTracker.Entries());
     }
 }
コード例 #51
0
        private static void TrackEntitiesWithKeyGenerationTest(Func<DbContext, TheGu, TheGu> adder)
        {
            using (var context = new EarlyLearningCenter(TestHelpers.Instance.CreateServiceProvider()))
            {
                var gu1 = new TheGu { ShirtColor = "Red" };
                var gu2 = new TheGu { ShirtColor = "Still Red" };

                Assert.Same(gu1, adder(context, gu1));
                Assert.Same(gu2, adder(context, gu2));
                Assert.NotEqual(default(Guid), gu1.Id);
                Assert.NotEqual(default(Guid), gu2.Id);
                Assert.NotEqual(gu1.Id, gu2.Id);

                var categoryEntry = context.Entry(gu1);
                Assert.Same(gu1, categoryEntry.Entity);
                Assert.Equal(EntityState.Added, categoryEntry.State);

                categoryEntry = context.Entry(gu2);
                Assert.Same(gu2, categoryEntry.Entity);
                Assert.Equal(EntityState.Added, categoryEntry.State);
            }
        }
コード例 #52
0
        private static void TrackMultipleEntitiesTestEnumerable(
            Action<DbContext, IEnumerable<object>> categoryAdder,
            Action<DbContext, IEnumerable<object>> productAdder, EntityState expectedState)
        {
            using (var context = new EarlyLearningCenter(TestHelpers.Instance.CreateServiceProvider()))
            {
                var category1 = new Category { Id = 1, Name = "Beverages" };
                var category2 = new Category { Id = 2, Name = "Foods" };
                var product1 = new Product { Id = 1, Name = "Marmite", Price = 7.99m };
                var product2 = new Product { Id = 2, Name = "Bovril", Price = 4.99m };

                categoryAdder(context, new List<Category> { category1, category2 });
                productAdder(context, new List<Product> { product1, product2 });

                Assert.Same(category1, context.Entry(category1).Entity);
                Assert.Same(category2, context.Entry(category2).Entity);
                Assert.Same(product1, context.Entry(product1).Entity);
                Assert.Same(product2, context.Entry(product2).Entity);

                Assert.Same(category1, context.Entry(category1).Entity);
                Assert.Equal(expectedState, context.Entry(category1).State);
                Assert.Same(category2, context.Entry(category2).Entity);
                Assert.Equal(expectedState, context.Entry(category2).State);

                Assert.Same(product1, context.Entry(product1).Entity);
                Assert.Equal(expectedState, context.Entry(product1).State);
                Assert.Same(product2, context.Entry(product2).Entity);
                Assert.Equal(expectedState, context.Entry(product2).State);
            }
        }
コード例 #53
0
        private static void TrackEntitiesTestNonGeneric(
            Func<DbContext, object, EntityEntry> categoryAdder,
            Func<DbContext, object, EntityEntry> productAdder, EntityState expectedState)
        {
            using (var context = new EarlyLearningCenter(TestHelpers.Instance.CreateServiceProvider()))
            {
                var category1 = new Category { Id = 1, Name = "Beverages" };
                var category2 = new Category { Id = 2, Name = "Foods" };
                var product1 = new Product { Id = 1, Name = "Marmite", Price = 7.99m };
                var product2 = new Product { Id = 2, Name = "Bovril", Price = 4.99m };

                var categoryEntry1 = categoryAdder(context, category1);
                var categoryEntry2 = categoryAdder(context, category2);
                var productEntry1 = productAdder(context, product1);
                var productEntry2 = productAdder(context, product2);

                Assert.Same(category1, categoryEntry1.Entity);
                Assert.Same(category2, categoryEntry2.Entity);
                Assert.Same(product1, productEntry1.Entity);
                Assert.Same(product2, productEntry2.Entity);

                Assert.Same(category1, categoryEntry1.Entity);
                Assert.Equal(expectedState, categoryEntry2.State);
                Assert.Same(category2, categoryEntry2.Entity);
                Assert.Equal(expectedState, categoryEntry2.State);

                Assert.Same(product1, productEntry1.Entity);
                Assert.Equal(expectedState, productEntry1.State);
                Assert.Same(product2, productEntry2.Entity);
                Assert.Equal(expectedState, productEntry2.State);

                Assert.Same(categoryEntry1.GetInfrastructure(), context.Entry(category1).GetInfrastructure());
                Assert.Same(categoryEntry2.GetInfrastructure(), context.Entry(category2).GetInfrastructure());
                Assert.Same(productEntry1.GetInfrastructure(), context.Entry(product1).GetInfrastructure());
                Assert.Same(productEntry2.GetInfrastructure(), context.Entry(product2).GetInfrastructure());
            }
        }
コード例 #54
0
        public void Replaced_services_are_scoped_appropriately()
        {
            var services = new ServiceCollection();

            services.AddEntityFramework()
            .UseClrCollectionAccessorSource <FakeClrCollectionAccessorSource>()
            .UseClrPropertyGetterSource <FakeClrPropertyGetterSource>()
            .UseClrPropertySetterSource <FakeClrPropertySetterSource>()
            .UseEntityKeyFactorySource <FakeEntityKeyFactorySource>()
            .UseEntityMaterializerSource <FakeEntityMaterializerSource>()
            .UseDbSetFinder <FakeDbSetFinder>()
            .UseDbSetInitializer <FakeDbSetInitializer>()
            .UseEntityStateListener <FakeEntityStateListener>()
            .UseLoggerFactory <FakeLoggerFactory>()
            .UseModelSource <FakeModelSource>()
            .UseStateEntryFactory <FakeStateEntryFactory>()
            .UseStateEntryNotifier <FakeStateEntryNotifier>()
            .UseContextSets <FakeContextSets>()
            .UseStateManager <FakeStateManager>()
            .UseEntityStateListener <FakeNavigationFixer>();

            var provider = services.BuildServiceProvider();

            StateEntryFactory    stateEntryFactory;
            StateEntryNotifier   stateEntryNotifier;
            ContextSets          contextSets;
            StateManager         stateManager;
            IEntityStateListener entityStateListener;

            var context       = new EarlyLearningCenter(provider);
            var configuration = context.Configuration;

            var clrCollectionAccessorSource = configuration.Services.ServiceProvider.GetService <ClrCollectionAccessorSource>();
            var clrPropertyGetterSource     = configuration.Services.ClrPropertyGetterSource;
            var clrPropertySetterSource     = configuration.Services.ClrPropertySetterSource;
            var entityKeyFactorySource      = configuration.Services.EntityKeyFactorySource;
            var entityMaterializerSource    = configuration.Services.ServiceProvider.GetService <EntityMaterializerSource>();
            var setFinder      = configuration.Services.ServiceProvider.GetService <DbSetFinder>();
            var setInitializer = configuration.Services.ServiceProvider.GetService <DbSetInitializer>();
            var loggerFactory  = configuration.Services.ServiceProvider.GetService <ILoggerFactory>();
            var modelSource    = configuration.Services.ModelSource;

            context.Dispose();

            context       = new EarlyLearningCenter(provider);
            configuration = context.Configuration;

            stateEntryFactory   = configuration.Services.StateEntryFactory;
            stateEntryNotifier  = configuration.Services.StateEntryNotifier;
            contextSets         = configuration.Services.ContextSets;
            stateManager        = configuration.Services.StateManager;
            entityStateListener = configuration.Services.EntityStateListeners.OfType <FakeNavigationFixer>().Single();

            Assert.Same(stateEntryFactory, configuration.Services.StateEntryFactory);
            Assert.Same(stateEntryNotifier, configuration.Services.StateEntryNotifier);
            Assert.Same(contextSets, configuration.Services.ContextSets);
            Assert.Same(stateManager, configuration.Services.StateManager);
            Assert.Same(entityStateListener, configuration.Services.EntityStateListeners.OfType <FakeNavigationFixer>().Single());

            Assert.Same(clrCollectionAccessorSource, configuration.Services.ServiceProvider.GetService <ClrCollectionAccessorSource>());
            Assert.Same(clrPropertyGetterSource, configuration.Services.ClrPropertyGetterSource);
            Assert.Same(clrPropertySetterSource, configuration.Services.ClrPropertySetterSource);
            Assert.Same(entityKeyFactorySource, configuration.Services.EntityKeyFactorySource);
            Assert.Same(entityMaterializerSource, configuration.Services.ServiceProvider.GetService <EntityMaterializerSource>());
            Assert.Same(setFinder, configuration.Services.ServiceProvider.GetService <DbSetFinder>());
            Assert.Same(setInitializer, configuration.Services.ServiceProvider.GetService <DbSetInitializer>());
            Assert.Same(loggerFactory, configuration.Services.ServiceProvider.GetService <ILoggerFactory>());
            Assert.Same(modelSource, configuration.Services.ModelSource);

            context.Dispose();

            context       = new EarlyLearningCenter(provider);
            configuration = context.Configuration;

            Assert.NotSame(stateEntryFactory, configuration.Services.StateEntryFactory);
            Assert.NotSame(stateEntryNotifier, configuration.Services.StateEntryNotifier);
            Assert.NotSame(contextSets, configuration.Services.ContextSets);
            Assert.NotSame(stateManager, configuration.Services.StateManager);
            Assert.NotSame(entityStateListener, configuration.Services.EntityStateListeners.OfType <FakeNavigationFixer>().Single());

            Assert.Same(clrCollectionAccessorSource, configuration.Services.ServiceProvider.GetService <ClrCollectionAccessorSource>());
            Assert.Same(clrPropertyGetterSource, configuration.Services.ClrPropertyGetterSource);
            Assert.Same(clrPropertySetterSource, configuration.Services.ClrPropertySetterSource);
            Assert.Same(entityKeyFactorySource, configuration.Services.EntityKeyFactorySource);
            Assert.Same(entityMaterializerSource, configuration.Services.ServiceProvider.GetService <EntityMaterializerSource>());
            Assert.Same(setFinder, configuration.Services.ServiceProvider.GetService <DbSetFinder>());
            Assert.Same(setInitializer, configuration.Services.ServiceProvider.GetService <DbSetInitializer>());
            Assert.Same(loggerFactory, configuration.Services.ServiceProvider.GetService <ILoggerFactory>());
            Assert.Same(modelSource, configuration.Services.ModelSource);

            context.Dispose();
        }
コード例 #55
0
 private static void TrackNoEntitiesTestEnumerable(
     Action<DbContext, IEnumerable<object>> categoryAdder,
     Action<DbContext, IEnumerable<object>> productAdder)
 {
     using (var context = new EarlyLearningCenter(TestHelpers.Instance.CreateServiceProvider()))
     {
         categoryAdder(context, new HashSet<Category>());
         productAdder(context, new HashSet<Product>());
         Assert.Empty(context.ChangeTracker.Entries());
     }
 }
コード例 #56
0
        public async Task SaveChangesAsync_only_passes_dirty_entries_to_Database()
        {
            var passedEntries = new List<IUpdateEntry>();
            var database = new Mock<IDatabase>();
            database.Setup(s => s.SaveChangesAsync(It.IsAny<IReadOnlyList<IUpdateEntry>>(), It.IsAny<CancellationToken>()))
                .Callback<IEnumerable<IUpdateEntry>, CancellationToken>((e, c) => passedEntries.AddRange(e))
                .Returns(Task.FromResult(3));

            var valueGenMock = new Mock<IValueGeneratorSelector>();
            valueGenMock.Setup(m => m.Select(It.IsAny<IProperty>(), It.IsAny<IEntityType>())).Returns(Mock.Of<ValueGenerator>());

            var servicesMock = new Mock<IDatabaseProviderServices>();
            servicesMock.Setup(m => m.Database).Returns(database.Object);
            servicesMock.Setup(m => m.ValueGeneratorSelector).Returns(valueGenMock.Object);
            servicesMock.Setup(m => m.ModelSource).Returns(new Mock<ModelSource>(new DbSetFinder(), new CoreConventionSetBuilder())
                { CallBase = true }.Object);
            servicesMock
                .Setup(m => m.ModelValidator)
                .Returns(new LoggingModelValidator(new Logger<LoggingModelValidator>(new LoggerFactory())));
                
            var sourceMock = new Mock<IDatabaseProvider>();
            sourceMock.Setup(m => m.IsConfigured(It.IsAny<IDbContextOptions>())).Returns(true);
            sourceMock.Setup(m => m.GetProviderServices(It.IsAny<IServiceProvider>())).Returns(servicesMock.Object);

            var services = new ServiceCollection();
            services.AddEntityFramework();
            services.AddInstance(sourceMock.Object);
            var serviceProvider = services.BuildServiceProvider();

            using (var context = new EarlyLearningCenter(serviceProvider, new DbContextOptionsBuilder().Options))
            {
                context.Entry(new Category { Id = 1 }).State = EntityState.Unchanged;
                context.Entry(new Category { Id = 2 }).State = EntityState.Modified;
                context.Entry(new Category { Id = 3 }).State = EntityState.Added;
                context.Entry(new Category { Id = 4 }).State = EntityState.Deleted;
                Assert.Equal(4, context.ChangeTracker.Entries().Count());

                await context.SaveChangesAsync();
            }

            Assert.Equal(3, passedEntries.Count);

            database.Verify(
                s => s.SaveChangesAsync(It.IsAny<IReadOnlyList<InternalEntityEntry>>(), It.IsAny<CancellationToken>()),
                Times.Once);
        }
コード例 #57
0
        private void ChangeStateWithMethod(Action<DbContext, object> action, EntityState initialState, EntityState expectedState)
        {
            using (var context = new EarlyLearningCenter(TestHelpers.Instance.CreateServiceProvider()))
            {
                var entity = new Category { Id = 1, Name = "Beverages" };
                var entry = context.Entry(entity);

                entry.State = initialState;

                action(context, entity);

                Assert.Equal(expectedState, entry.State);
            }
        }
コード例 #58
0
 public void Default_services_are_registered_when_parameterless_constructor_used()
 {
     using (var context = new EarlyLearningCenter())
     {
         Assert.IsType<KeyValueFactorySource>(context.GetService<IKeyValueFactorySource>());
     }
 }
コード例 #59
0
        [Fact] // Issue #1246
        public void Can_set_set_to_Unchanged_with_inconsistent_FK_principal_first_fully_fixed_up()
        {
            using (var context = new EarlyLearningCenter(TestHelpers.Instance.CreateServiceProvider()))
            {
                var category = new Category { Id = 1, Name = "Beverages" };
                var product = new Product { Id = 1, CategoryId = 7, Name = "Marmite", Category = category };
                category.Products = new List<Product> { product };

                context.Entry(category).State = EntityState.Unchanged;

                Assert.Equal(7, product.CategoryId);
                Assert.Same(product, category.Products.Single());
                Assert.Same(category, product.Category);
                Assert.Equal(EntityState.Unchanged, context.Entry(category).State);
                Assert.Equal(EntityState.Detached, context.Entry(product).State);

                context.Entry(product).State = EntityState.Unchanged;

                Assert.Equal(7, product.CategoryId);
                Assert.Same(product, category.Products.Single());
                Assert.Same(category, product.Category);
                Assert.Equal(EntityState.Unchanged, context.Entry(category).State);

                // Dependent is Unchanged here because the FK change happened before it was attached
                Assert.Equal(EntityState.Unchanged, context.Entry(product).State);
            }
        }
コード例 #60
0
        public void Entry_methods_check_arguments()
        {
            var services = new ServiceCollection()
                .AddScoped<IStateManager, FakeStateManager>();

            var serviceProvider = TestHelpers.Instance.CreateServiceProvider(services);

            using (var context = new EarlyLearningCenter(serviceProvider))
            {
                Assert.Equal(
                    "entity",
                    // ReSharper disable once AssignNullToNotNullAttribute
                    Assert.Throws<ArgumentNullException>(() => context.Entry(null)).ParamName);
                Assert.Equal(
                    "entity",
                    // ReSharper disable once AssignNullToNotNullAttribute
                    Assert.Throws<ArgumentNullException>(() => context.Entry<Random>(null)).ParamName);
            }
        }