Exemplo n.º 1
0
        public void CacheKnowsWhenDataIsDeletedInDb()
        {
            // Create initial data in database
            int sueID = CustomerHelpers.AddCustomer("Sue", "VA");

            using (var context1 = new EFTestContext())
            {
                // Get Sue's customer entity
                var sue = context1.Customers.First(c => c.ID == sueID);
                // Name should be "Sue"
                sue.Name.Should().Be("Sue");

                // Delete data using other context (simulating a second user)
                using (var context2 = new EFTestContext())
                {
                    var sueToDelete = context2.Customers.First(c => c.ID == sueID);
                    context2.Customers.Remove(sueToDelete);
                    context2.SaveChanges();
                }

                // Verify record has been deleted from the database
                using (var context3 = new EFTestContext())
                {
                    var sueIsDeleted = context3.Customers.FirstOrDefault(c => c.ID == sueID);
                    sueIsDeleted.Should().BeNull();
                }

                // And our original context shows the record as deleted
                var sueNotDeleted = context1.Customers.FirstOrDefault(c => c.ID == sueID);
                sueNotDeleted.Should().BeNull();
            }
        }
Exemplo n.º 2
0
        public void CacheKnowsWhenDataIsAddedToDb()
        {
            // Create initial data in database
            int sueID = CustomerHelpers.AddCustomer("Sue", "VA");

            using (var context1 = new EFTestContext())
            {
                // Get count of customers in Virginia
                var numInVABefore = context1.Customers.Where(c => c.State == "VA").ToList().Count;

                // Add new customer using separate context (simulating a second user)
                int jamesID = CustomerHelpers.AddCustomer("James", "VA");

                // Verify new record exists in database using another context
                using (var context3 = new EFTestContext())
                {
                    var jamesExists = context3.Customers.FirstOrDefault(c => c.ID == jamesID);
                    jamesExists.Should().NotBeNull();
                }

                // Our original context shows the new record when queried
                var numInVAAfter = context1.Customers.Where(c => c.State == "VA").ToList().Count;
                numInVAAfter.Should().Be(numInVABefore + 1);
            }

            // Cleanup
            CustomerHelpers.DeleteCustomer(sueID);
        }
Exemplo n.º 3
0
        public void AsNoTrackingDoesntAddDataToCache()
        {
            // Create initial data in database
            int sueID = CustomerHelpers.AddCustomer("Sue", "VA");

            using (var context1 = new EFTestContext())
            {
                // Get Sue's customer entity
                var sue = context1.Customers.Where(c => c.ID == sueID).AsNoTracking().First();
                // Name should be "Sue"
                sue.Name.Should().Be("Sue");

                // Update data in other context (simulating a second user)
                using (var context2 = new EFTestContext())
                {
                    context2.Customers.First(c => c.ID == sueID).Name = "Susan";
                    context2.SaveChanges();
                }

                // Verify the name has been updated in the database
                using (var context3 = new EFTestContext())
                {
                    var sueIsUpdated = context3.Customers.First(c => c.ID == sueID);
                    sueIsUpdated.Name.Should().Be("Susan");
                }

                // We can retrieve the updated record from context1, which tells us that the
                // cache on context1 is empty (before we retrieved the data
                var sueStillUpdated = context1.Customers.First(c => c.ID == sueID);
                sueStillUpdated.Name.Should().Be("Susan");
            }

            // Cleanup
            CustomerHelpers.DeleteCustomer(sueID);
        }
Exemplo n.º 4
0
        public void UsingANewContextWillRetrieveUpdatedData()
        {
            // Create initial data in database
            int sueID = CustomerHelpers.AddCustomer("Sue", "VA");

            using (var context1 = new EFTestContext())
            {
                // Get Sue's customer entity
                var sue = context1.Customers.Where(c => c.ID == sueID).AsNoTracking().First();
                // Name should be "Sue"
                sue.Name.Should().Be("Sue");
            }

            // Update data in other context (simulating a second user)
            using (var context2 = new EFTestContext())
            {
                context2.Customers.First(c => c.ID == sueID).Name = "Susan";
                context2.SaveChanges();
            }

            // Use a new context to retrieve the updated record
            using (var context3 = new EFTestContext())
            {
                var sueIsUpdated = context3.Customers.First(c => c.ID == sueID);
                sueIsUpdated.Name.Should().Be("Susan");
            }

            // Cleanup
            CustomerHelpers.DeleteCustomer(sueID);
        }
Exemplo n.º 5
0
        public void UsingANewContextWillNotShowDeletedData()
        {
            // Create initial data in database
            int      sueID = CustomerHelpers.AddCustomer("Sue", "VA");
            Customer originalSue;

            using (var context1 = new EFTestContext())
            {
                // Get Sue's customer entity
                originalSue = context1.Customers.Where(c => c.ID == sueID).AsNoTracking().First();
                // Name should be "Sue"
                originalSue.Name.Should().Be("Sue");
            }

            // Delete data in other context (simulating a second user)
            using (var context2 = new EFTestContext())
            {
                var existingSue = context2.Customers.First(c => c.ID == sueID);
                context2.Customers.Remove(existingSue);
                context2.SaveChanges();
            }

            // Use a new context to retrieve the updated record
            using (var context3 = new EFTestContext())
            {
                var sueIsDeleted = context3.Customers.FirstOrDefault(c => c.ID == sueID);
                sueIsDeleted.Should().BeNull();
            }

            // Caution: the original entity you retrieved is still around, but not in the cache
            originalSue.Should().NotBeNull();
        }
Exemplo n.º 6
0
        public void BulkInsert()
        {
            const int perInsertCount = 100000;
            using (EFTestContext context = new EFTestContext())
            {
                for (int i = 0; i < 100; i++)
                {
                    List<UserContract> users = new List<UserContract>(perInsertCount + 1);
                    for (int j = 0; j < perInsertCount; j++)
                    {
                        var user = new UserContract
                        {
                            Name = "nlh" + j + 1,
                            CardId = "11111",
                            Password = "******",
                            CreatedOn = DateTime.Now
                        };
                        //context.User.Add(user);   //直接插入上下文,下面调用SaveChanges(),BulkSaveChanges()更新
                        users.Add(user);
                    }
                    //context.SaveChanges();
                    context.BulkInsert(users);  //context.BulkSaveChanges();  没有context.BulkInsert(users);快

                }
            }
        }
Exemplo n.º 7
0
        public void AsNoTrackingDoesntReturnDeletedData()
        {
            // Create initial data in database
            int sueID = CustomerHelpers.AddCustomer("Sue", "VA");

            using (var context1 = new EFTestContext())
            {
                // Get Sue's customer entity
                var sue = context1.Customers.Where(c => c.ID == sueID).AsNoTracking().First();
                // Name should be "Sue"
                sue.Name.Should().Be("Sue");

                // Update data in other context (simulating a second user)
                using (var context2 = new EFTestContext())
                {
                    context2.Customers.First(c => c.ID == sueID).Name = "Susan";
                    context2.SaveChanges();
                }

                // Verify the name has been updated in the database
                using (var context3 = new EFTestContext())
                {
                    var sueIsUpdated = context3.Customers.First(c => c.ID == sueID);
                    sueIsUpdated.Name.Should().Be("Susan");
                }

                // But our original context has the stale data cached
                var sueStillUpdated = context1.Customers.First(c => c.ID == sueID);
                sueStillUpdated.Name.Should().Be("Susan");
            }

            // Cleanup
            CustomerHelpers.DeleteCustomer(sueID);
        }
Exemplo n.º 8
0
        private void RegisterQueryableRepository <TEntity>() where TEntity : class, IQueryableAggregateRoot
        {
            _container.RegisterType <IQuery <TEntity>, EntityFrameworkCodeFirstQueryable <TEntity> >();
            EFTestContext    context = _container.Resolve <EFTestContext>();
            IQuery <TEntity> query   = _container.Resolve <IQuery <TEntity> >(new ParameterOverride("dbContext", context));
            var injectionConstructor = new InjectionConstructor(query);

            _container.RegisterType <IQueryableRepository <TEntity>, QueryableRepository <TEntity> >(injectionConstructor);
        }
Exemplo n.º 9
0
        //The solution to handle multiple overloaded constructors using unity is available at
        // http://stackoverflow.com/questions/4059991/microsoft-unity-how-to-specify-a-certain-parameter-in-constructor

        private void RegisterCommandRepository <TEntity>(bool isUnitOfWorkRequired = false) where TEntity : BaseEntity <int>, ICommandAggregateRoot
        {
            _container.RegisterType <ICommand <TEntity>, EntityFrameworkCodeFirstCommand <TEntity, int> >();
            EFTestContext        context              = _container.Resolve <EFTestContext>();
            ICommand <TEntity>   command              = _container.Resolve <ICommand <TEntity> >(new ParameterOverride("dbContext", context));
            string               respositoryName      = isUnitOfWorkRequired ? REPOSITORY_WITH_UNIT_OF_WORK : REPOSITORY_WITHOUT_UNIT_OF_WORK;
            InjectionConstructor injectionConstructor = !isUnitOfWorkRequired ? new InjectionConstructor(command) : new InjectionConstructor(typeof(IUnitOfWork), command);

            _container.RegisterType <ICommandRepository <TEntity>, CommandRepository <TEntity> >(respositoryName, injectionConstructor);
        }
Exemplo n.º 10
0
 public SQLUnitOfWork(IClientsRepository ClientsRepository, IAgreementRepository AgreementRepository,
                      IAgreementDetailsRepository AgreementDetailsRepository, IProductsRepository ProductsRepository,
                      EFTestContext context)
 {
     _ClientsRepository          = ClientsRepository;
     _AgreementRepository        = AgreementRepository;
     _AgreementDetailsRepository = AgreementDetailsRepository;
     _ProductsRepository         = ProductsRepository;
     _context = context;
 }
Exemplo n.º 11
0
 public static void DeleteCustomer(int customerID)
 {
     // Cleanup
     using (var contextCleanup = new EFTestContext())
     {
         var sue = contextCleanup.Customers.First(c => c.ID == customerID);
         contextCleanup.Customers.Remove(sue);
         contextCleanup.SaveChanges();
     }
 }
Exemplo n.º 12
0
 public static int AddCustomer(string name, string state)
 {
     using (var context = new EFTestContext())
     {
         // Create initial data
         var newCustomer = context.Customers.Add(new Data.Models.Customer()
         {
             Name = name, State = state
         });
         context.SaveChanges();
         return(newCustomer.ID);
     }
 }
Exemplo n.º 13
0
 public int InsertUseByEF(int i)
 {
     using (EFTestContext context = new EFTestContext())
     {
         var user = new UserContract
         {
             Name = "InsertUseByEF" + i,
             CardId = "11111",
             Password = "******",
             CreatedOn = DateTime.Now
         };
         context.User.Add(user);
         return context.SaveChanges();
     }
 }
Exemplo n.º 14
0
        public void QueryWithOverwriteChangesWillUpdateCacheFromDatabase()
        {
            // Create initial data in database
            int sueID = CustomerHelpers.AddCustomer("Sue", "VA");

            using (var context1 = new EFTestContext())
            {
                // Get Sue's customer entity, adding it to the cache
                var sue = context1.Customers.First(c => c.ID == sueID);
                // Name should be "Sue"
                sue.Name.Should().Be("Sue");

                // Update data in other context (simulating a second user)
                using (var context2 = new EFTestContext())
                {
                    context2.Customers.First(c => c.ID == sueID).Name = "Susan";
                    context2.SaveChanges();
                }

                // Verify the name has been updated in the database
                using (var context3 = new EFTestContext())
                {
                    var sueIsUpdated = context3.Customers.First(c => c.ID == sueID);
                    sueIsUpdated.Name.Should().Be("Susan");
                }

                // Get Sue's customer entity using MergeOptions.OverwriteChanges, updating the entity in the cache
                var objectContext = ((IObjectContextAdapter)context1).ObjectContext;
                var objectQuery   = objectContext.CreateObjectSet <Customer>().Where(c => c.ID == sueID);
                // Set the MergeOptions to overwrite what is in the cache
                (objectQuery as ObjectQuery <Customer>).MergeOption = MergeOption.OverwriteChanges;
                var sueFromOriginalContext = objectQuery.First();
                // Verify we retrieved the updated data
                sueFromOriginalContext.Name.Should().Be("Susan");

                // Get Sue from the cache again, verifying that the cache has been updated, this tme
                // querying without the OverwriteChanges MergeOption
                var sueFromOriginalContextWithoutOverwriteChanges = context1.Customers.First(c => c.ID == sueID);
                sueFromOriginalContextWithoutOverwriteChanges.Name.Should().Be("Susan");
            }

            // Cleanup
            CustomerHelpers.DeleteCustomer(sueID);
        }
Exemplo n.º 15
0
        public void QueryWithOverwriteChangesWillShowDeletedEntitiesAsDeleted()
        {
            // Create initial data in database
            int sueID = CustomerHelpers.AddCustomer("Sue", "VA");

            using (var context1 = new EFTestContext())
            {
                // Get Sue's customer entity, adding it to the cache
                var sue = context1.Customers.First(c => c.ID == sueID);
                // Name should be "Sue"
                sue.Name.Should().Be("Sue");

                // Delete data in other context (simulating a second user)
                using (var context2 = new EFTestContext())
                {
                    var sueToDelete = context2.Customers.First(c => c.ID == sueID);
                    context2.Customers.Remove(sueToDelete);
                    context2.SaveChanges();
                }

                // Verify the data has been deleted from the database
                using (var context3 = new EFTestContext())
                {
                    var sueIsDeleted = context3.Customers.FirstOrDefault(c => c.ID == sueID);
                    sueIsDeleted.Should().BeNull();
                }

                // Get Sue's customer entity using MergeOptions.OverwriteChanges, updating the entity in the cache
                var objectContext = ((IObjectContextAdapter)context1).ObjectContext;
                var objectQuery   = objectContext.CreateObjectSet <Customer>().Where(c => c.ID == sueID);
                // Set the MergeOptions to overwrite what is in the cache
                (objectQuery as ObjectQuery <Customer>).MergeOption = MergeOption.OverwriteChanges;
                var sueFromOriginalContext = objectQuery.FirstOrDefault();
                // Verify that sue does not exist
                sueFromOriginalContext.Should().BeNull();

                // Caution: the original sue object we created doesn't know it's been deleted
                context1.Entry(sue).State.Should().Be(EntityState.Unchanged);
                // Caution: The original object still exists
                sue.Should().NotBeNull();
                sue.Name.Should().Be("Sue");
            }
        }
Exemplo n.º 16
0
        public void ReloadEntityWillForceEFToUpdateEntityInCache()
        {
            // Create initial data in database
            int sueID = CustomerHelpers.AddCustomer("Sue", "VA");

            using (var context1 = new EFTestContext())
            {
                // Get Sue's customer entity
                var sue = context1.Customers.Where(c => c.ID == sueID).First();
                // Name should be "Sue"
                sue.Name.Should().Be("Sue");

                // Update data in other context (simulating a second user)
                using (var context2 = new EFTestContext())
                {
                    context2.Customers.First(c => c.ID == sueID).Name = "Susan";
                    context2.SaveChanges();
                }

                // Verify the name has been updated in the database
                using (var context3 = new EFTestContext())
                {
                    var sueIsUpdated = context3.Customers.First(c => c.ID == sueID);
                    sueIsUpdated.Name.Should().Be("Susan");
                }

                // Verify our original context has the old data
                var sueNotUpdated = context1.Customers.First(c => c.ID == sueID);
                sueNotUpdated.Name.Should().Be("Sue");

                // Force EF to reload Sue's data
                context1.Entry(sue).Reload();

                // Retrieve the updated record from context1, which shows us
                // that the cache has been updated
                var sueUpdatedInOriginalContext = context1.Customers.First(c => c.ID == sueID);
                sueUpdatedInOriginalContext.Name.Should().Be("Susan");
            }

            // Cleanup
            CustomerHelpers.DeleteCustomer(sueID);
        }
Exemplo n.º 17
0
        public void GetDatabaseValuesWillUpdateTheCache()
        {
            // Create initial data in database
            int sueID = CustomerHelpers.AddCustomer("Sue", "VA");

            using (var context1 = new EFTestContext())
            {
                // Get Sue's customer entity
                var sue = context1.Customers.First(c => c.ID == sueID);
                // Name should be "Sue"
                sue.Name.Should().Be("Sue");

                // Update data in other context (simulating a second user)
                using (var context2 = new EFTestContext())
                {
                    context2.Customers.First(c => c.ID == sueID).Name = "Susan";
                    context2.SaveChanges();
                }

                // Verify the name has been updated in the database
                using (var context3 = new EFTestContext())
                {
                    var sueIsUpdated = context3.Customers.First(c => c.ID == sueID);
                    sueIsUpdated.Name.Should().Be("Susan");
                }

                // Verify we still have stale data in the cache
                var sueNotUpdated = context1.Customers.First(c => c.ID == sueID);
                sueNotUpdated.Name.Should().Be("Sue");

                // Use GetDatabaseValues to get a dictionary of the current db values (ignoring the cache)
                DbPropertyValues sueDbValues = context1.Entry(sueNotUpdated).GetDatabaseValues();
                sueDbValues["Name"].Should().Be("Susan");

                // Verify we still have stale data in the cache
                var sueStillNotUpdated = context1.Customers.First(c => c.ID == sueID);
                sueStillNotUpdated.Name.Should().Be("Sue");
            }

            // Cleanup
            CustomerHelpers.DeleteCustomer(sueID);
        }
Exemplo n.º 18
0
        public void StandardQueryWillNotOverwriteCacheAfterQueryWithOverwriteChanges()
        {
            // Create initial data in database
            int sueID = CustomerHelpers.AddCustomer("Sue", "VA");

            using (var context1 = new EFTestContext())
            {
                // Get Sue's customer entity using MergeOptions.OverwriteChanges, placing the entity in the cache
                var objectContext = ((IObjectContextAdapter)context1).ObjectContext;
                var objectQuery   = objectContext.CreateObjectSet <Customer>().Where(c => c.ID == sueID);
                // Set the MergeOptions to overwrite what is in the cache
                (objectQuery as ObjectQuery <Customer>).MergeOption = MergeOption.OverwriteChanges;
                var sueNowInCache = objectQuery.First();
                // Verify we retrieved the original data
                sueNowInCache.Name.Should().Be("Sue");

                // Update data in other context (simulating a second user)
                using (var context2 = new EFTestContext())
                {
                    context2.Customers.First(c => c.ID == sueID).Name = "Susan";
                    context2.SaveChanges();
                }

                // Verify the name has been updated in the database
                using (var context3 = new EFTestContext())
                {
                    var sueIsUpdated = context3.Customers.First(c => c.ID == sueID);
                    sueIsUpdated.Name.Should().Be("Susan");
                }

                // Get Sue from the cache without the OverwriteChanges MergeOption
                var sueFromOriginalContext = context1.Customers.First(c => c.ID == sueID);
                // We should see the original data, because the cache hasn't been updated
                sueFromOriginalContext.Name.Should().Be("Sue");
            }

            // Cleanup
            CustomerHelpers.DeleteCustomer(sueID);
        }
Exemplo n.º 19
0
 public GenericRepository(EFTestContext context)
 {
     _context = context;
     dbSet    = context.Set <T>();
 }
Exemplo n.º 20
0
 public ClientsRepository(EFTestContext context) : base(context)
 {
 }
Exemplo n.º 21
0
 public AgreementRepository(EFTestContext context) : base(context)
 {
 }
Exemplo n.º 22
0
        public void RefreshingMultipleEntitiesInEFWillForceEFToUpdateEntityInCache()
        {
            try
            {
                // Create initial data in database
                int sueID = CustomerHelpers.AddCustomer("Sue", "VA");
                int jimID = CustomerHelpers.AddCustomer("Jim", "VA");

                using (var context1 = new EFTestContext())
                {
                    // Get Sue's and Jim's customer entities
                    var sue = context1.Customers.Where(c => c.ID == sueID).First();
                    var jim = context1.Customers.Where(c => c.ID == jimID).First();
                    // Name should be "Sue"/"Jim"
                    sue.Name.Should().Be("Sue");
                    jim.Name.Should().Be("Jim");

                    // Update data in other context (simulating a second user)
                    using (var context2 = new EFTestContext())
                    {
                        context2.Customers.First(c => c.ID == sueID).Name = "Susan";
                        context2.Customers.First(c => c.ID == jimID).Name = "James";
                        context2.SaveChanges();
                    }

                    // Verify the name has been updated in the database
                    using (var context3 = new EFTestContext())
                    {
                        var sueIsUpdated = context3.Customers.First(c => c.ID == sueID);
                        sueIsUpdated.Name.Should().Be("Susan");
                        var jimIsUpdated = context3.Customers.First(c => c.ID == jimID);
                        jimIsUpdated.Name.Should().Be("James");
                    }

                    // Verify our original context has the old data
                    var sueNotUpdated = context1.Customers.First(c => c.ID == sueID);
                    sueNotUpdated.Name.Should().Be("Sue");
                    var jimNotUpdated = context1.Customers.First(c => c.ID == jimID);
                    jimNotUpdated.Name.Should().Be("Jim");

                    // Force EF to refresh Sue's and Jim's data
                    var objectContext    = ((IObjectContextAdapter)context1).ObjectContext;
                    var objectsToRefresh = new Customer[] { jim, sue };
                    objectContext.Refresh(RefreshMode.StoreWins, objectsToRefresh);

                    // You can also query the ObjectStateManager for the objects you need to refresh
                    //var objectsToRefresh = objectContext.ObjectStateManager.GetObjectStateEntries(
                    //	EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged)
                    //	.Where(e => e.EntityKey != null)
                    //	.Select(e => e.Entity)
                    //	.OfType<Customer>()
                    //	.Where(c => (new int[] {sueID, jimID}).Contains(c.ID));
                    //objectContext.Refresh(RefreshMode.StoreWins, objectsToRefresh);

                    // Verify our original context has the new data
                    var sueUpdatedInOriginalContext = context1.Customers.First(c => c.ID == sueID);
                    sueUpdatedInOriginalContext.Name.Should().Be("Susan");
                    var jimUpdatedInOriginalContext = context1.Customers.First(c => c.ID == jimID);
                    jimUpdatedInOriginalContext.Name.Should().Be("James");
                }

                // Cleanup
                CustomerHelpers.DeleteCustomer(sueID);
                CustomerHelpers.DeleteCustomer(jimID);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 23
0
 public ProductsRepository(EFTestContext context) : base(context)
 {
 }
Exemplo n.º 24
0
 public void TransactionTestStart()
 {
     context     = new EFTestContext();
     transaction = context.Database.BeginTransaction();
 }