A LazyInternalContext is a concrete InternalContext type that will lazily create the underlying ObjectContext when needed. The ObjectContext created is owned by the internal context and will be disposed when the internal context is disposed.
Inheritance: InternalContext
Ejemplo n.º 1
0
        public void CreateModel_uses_DbCompiledModel_from_ModelStore_when_available()
        {
            var store = new Mock <DbModelStore>();

            var dbCompiledModelInStore = new DbCompiledModel();

            store.Setup(c => c.TryLoad(It.IsAny <Type>())).Returns(dbCompiledModelInStore);
            store.Setup(c => c.Save(It.IsAny <Type>(), It.IsAny <DbModel>()));

            try
            {
                var dependencyResolver = new SingletonDependencyResolver <DbModelStore>(store.Object);
                MutableResolver.AddResolver <DbModelStore>(dependencyResolver);

                var mockContext = new Mock <LazyInternalContext>(
                    new Mock <DbContext>().Object, new Mock <IInternalConnection>().Object, null, null, null, null, null)
                {
                    CallBase = true
                };

                var model = LazyInternalContext.CreateModel(mockContext.Object);

                Assert.Same(dbCompiledModelInStore, model);

                store.Verify(c => c.TryLoad(It.IsAny <Type>()), Times.Once(),
                             "should load existing model");

                store.Verify(c => c.Save(It.IsAny <Type>(), It.IsAny <DbModel>()), Times.Never(),
                             "should not call Save when loading model from store");
            }
            finally //clean up
            {
                MutableResolver.ClearResolvers();
            }
        }
Ejemplo n.º 2
0
        public void CreateModel_saves_DbCompiledModel_into_ModelStore_when_not_yet_stored()
        {
            var store = new Mock <DbModelStore>();

            store.Setup(c => c.TryLoad(It.IsAny <Type>())).Returns((DbCompiledModel)null); //no file exists yet
            store.Setup(c => c.Save(It.IsAny <Type>(), It.IsAny <DbModel>()));

            try
            {
                var dependencyResolver = new SingletonDependencyResolver <DbModelStore>(store.Object);
                MutableResolver.AddResolver <DbModelStore>(dependencyResolver);

                var mockContext = new Mock <LazyInternalContext>(
                    new Mock <DbContext>().Object, new Mock <IInternalConnection>().Object, null, null, null, null, null)
                {
                    CallBase = true
                };
                mockContext.Object.ModelProviderInfo = ProviderRegistry.Sql2008_ProviderInfo;

                var model = LazyInternalContext.CreateModel(mockContext.Object);

                Assert.NotNull(model);

                store.Verify(c => c.TryLoad(It.IsAny <Type>()), Times.Once(),
                             "should try to load existing model");

                store.Verify(c => c.Save(It.IsAny <Type>(), It.IsAny <DbModel>()), Times.Once(),
                             "should Save after creating model when store did not contain exist yet");
            }
            finally //clean up
            {
                MutableResolver.ClearResolvers();
            }
        }
        public void Setting_log_again_reoplaces_the_existing_sink()
        {
            var mockDispatchers = new Mock <Dispatchers>(null);

            var context         = new Mock <DbContext>().Object;
            var internalContext = new LazyInternalContext(
                context, new Mock <IInternalConnection>().Object, null, null, null, new Lazy <Dispatchers>(() => mockDispatchers.Object));

            Action <string> sink = new StringWriter().Write;

            internalContext.Log = sink;

            Action <string> newSink = new StringWriter().Write;

            internalContext.Log = newSink;

            mockDispatchers.Verify(
                m => m.RemoveInterceptor(It.Is <DbCommandLogger>(l => l.Context == context && l.Sink == sink)),
                Times.Once());

            mockDispatchers.Verify(
                m => m.AddInterceptor(It.Is <DbCommandLogger>(l => l.Context == context && l.Sink == newSink)),
                Times.Once());

            mockDispatchers.Verify(
                m => m.AddInterceptor(It.Is <DbCommandLogger>(l => l.Context == context)),
                Times.Exactly(2));
        }
        // <summary>
        // Creates an immutable, cacheable representation of the model defined by this builder.
        // This model can be used to create an <see cref="ObjectContext" /> or can be passed to a <see cref="DbContext" />
        // constructor to create a <see cref="DbContext" /> for this model.
        // </summary>
        public static DbCompiledModel CreateModel(LazyInternalContext internalContext)
        {
            var contextType = internalContext.Owner.GetType();

            DbModelStore modelStore = null;

            if (!(internalContext.Owner is HistoryContext))
            {
                modelStore = DbConfiguration.DependencyResolver.GetService <DbModelStore>();
                if (modelStore != null)
                {
                    var compiledModel = modelStore.TryLoad(contextType);
                    if (compiledModel != null)
                    {
                        return(compiledModel);
                    }
                }
            }

            var modelBuilder = internalContext.CreateModelBuilder();

            var model
                = (internalContext._modelProviderInfo == null)
                      ? modelBuilder.Build(internalContext._internalConnection.Connection)
                      : modelBuilder.Build(internalContext._modelProviderInfo);

            internalContext._modelBeingInitialized = model;

            if (modelStore != null)
            {
                modelStore.Save(contextType, model);
            }

            return(model.Compile());
        }
Ejemplo n.º 5
0
        public static DbCompiledModel CreateModel(LazyInternalContext internalContext)
        {
            DbModelBuilder modelBuilder = internalContext.CreateModelBuilder();
            DbModel        dbModel      = internalContext._modelProviderInfo == null?modelBuilder.Build(internalContext._internalConnection.Connection) : modelBuilder.Build(internalContext._modelProviderInfo);

            internalContext._modelBeingInitialized = dbModel;
            return(dbModel.Compile());
        }
Ejemplo n.º 6
0
        /// <summary>
        ///     Creates an immutable, cacheable representation of the model defined by this builder.
        ///     This model can be used to create an <see cref="ObjectContext" /> or can be passed to a <see cref="DbContext" />
        ///     constructor to create a <see cref="DbContext" /> for this model.
        /// </summary>
        public static DbCompiledModel CreateModel(LazyInternalContext internalContext)
        {
            var modelBuilder = internalContext.CreateModelBuilder();

            var model
                = (internalContext._modelProviderInfo == null)
                      ? modelBuilder.Build(internalContext._internalConnection.Connection)
                      : modelBuilder.Build(internalContext._modelProviderInfo);

            return(model.Compile());
        }
        public void Log_can_be_cleared_by_setting_it_to_null()
        {
            var mockDispatchers = new Mock <Dispatchers>(null);

            var context         = new Mock <DbContext>().Object;
            var internalContext = new LazyInternalContext(
                context, new Mock <IInternalConnection>().Object, null, null, null, new Lazy <Dispatchers>(() => mockDispatchers.Object));

            Action <string> sink = new StringWriter().Write;

            internalContext.Log = sink;
            internalContext.Log = null;

            mockDispatchers.Verify(
                m => m.RemoveInterceptor(It.Is <DbCommandLogger>(l => l.Context == context && l.Sink == sink)),
                Times.Once());
        }
        public void Log_returns_the_current_sink_in_use_or_null()
        {
            var mockDispatchers = new Mock <Dispatchers>(null);

            var context         = new Mock <DbContext>().Object;
            var internalContext = new LazyInternalContext(
                context, new Mock <IInternalConnection>().Object, null, null, null, new Lazy <Dispatchers>(() => mockDispatchers.Object));

            Assert.Null(internalContext.Log);

            Action <string> sink = new StringWriter().Write;

            internalContext.Log = sink;
            Assert.Same(sink, internalContext.Log);

            internalContext.Log = null;
            Assert.Null(internalContext.Log);
        }
Ejemplo n.º 9
0
            public void Log_is_cleared_when_context_is_disposed()
            {
                var mockDispatchers = new Mock <DbDispatchers>();

                var context         = new Mock <DbContext>().Object;
                var internalContext = new LazyInternalContext(
                    context, new Mock <IInternalConnection>().Object, null, null, null, new Lazy <DbDispatchers>(() => mockDispatchers.Object));

                Action <string> sink = new StringWriter().Write;

                internalContext.Log = sink;

                internalContext.Dispose();

                mockDispatchers.Verify(
                    m => m.RemoveInterceptor(It.Is <DatabaseLogFormatter>(l => l.Context == context && l.WriteAction == sink)),
                    Times.Once());
            }
Ejemplo n.º 10
0
        public void Dispose_calls_EntityConnection_dispose_before_InternalConnection_dispose()
        {
            var results = new List <string>();

            var underlyingConnection = new Mock <DbConnection>();

            var lazyInternalConnectionMock = new Mock <LazyInternalConnection>("fake");

            lazyInternalConnectionMock.SetupGet(ic => ic.Connection).Returns(underlyingConnection.Object);
            lazyInternalConnectionMock.Setup(ic => ic.Dispose()).Callback(() => results.Add("LazyInternalConnection Dispose() called"));

            var metadataWorkspaceMock = new Mock <MetadataWorkspace>();

            metadataWorkspaceMock.Setup(mw => mw.GetItemCollection(DataSpace.CSSpace)).Returns(() => null);

            var dbContext = new TestDbContext();

            var entityConnectionMock = new Mock <EntityConnection>();

            entityConnectionMock.SetupGet(ec => ec.ConnectionString).Returns("fake");
            entityConnectionMock.Setup(ec => ec.GetMetadataWorkspace()).Returns(metadataWorkspaceMock.Object);
            entityConnectionMock.Protected().Setup("Dispose", ItExpr.IsAny <bool>()).
            Callback <bool>(b => results.Add("EntityConnection Dispose() called"));

            var objectContextMock = new Mock <ObjectContext>(entityConnectionMock.Object, true)
            {
                CallBase = true
            };

            objectContextMock.SetupGet(oc => oc.MetadataWorkspace).Returns(metadataWorkspaceMock.Object);

            var lazyInternalContext = new LazyInternalContext(
                dbContext, lazyInternalConnectionMock.Object, null, null, null, null, objectContextMock.Object);

            lazyInternalContext.DisposeContext(true);

            Assert.Equal(2, results.Count);
            Assert.Same("EntityConnection Dispose() called", results[0]);
            Assert.Same("LazyInternalConnection Dispose() called", results[1]);
        }
        public void Log_can_be_set_to_log_to_a_new_sink()
        {
            var mockDispatchers = new Mock <Dispatchers>(null);

            var context         = new Mock <DbContext>().Object;
            var internalContext = new LazyInternalContext(
                context, new Mock <IInternalConnection>().Object, null, null, null, new Lazy <Dispatchers>(() => mockDispatchers.Object));

            Action <string> sink = new StringWriter().Write;

            internalContext.Log = sink;

            mockDispatchers.Verify(
                m => m.AddInterceptor(It.Is <DbCommandLogger>(l => l.Context == context && l.Sink == sink)),
                Times.Once());

            // Setting same sink again is a no-op
            internalContext.Log = sink;

            mockDispatchers.Verify(
                m => m.AddInterceptor(It.Is <DbCommandLogger>(l => l.Context == context && l.Sink == sink)),
                Times.Once());
        }
Ejemplo n.º 12
0
        public void CreateModel_does_not_use_ModelStore_for_HistoryContext()
        {
            var store = new Mock <DbModelStore>();

            var dbCompiledModelInStore = new DbCompiledModel();

            store.Setup(c => c.TryLoad(It.IsAny <Type>())).Returns(dbCompiledModelInStore);
            store.Setup(c => c.Save(It.IsAny <Type>(), It.IsAny <DbModel>()));

            try
            {
                var dependencyResolver = new SingletonDependencyResolver <DbModelStore>(store.Object);
                MutableResolver.AddResolver <DbModelStore>(dependencyResolver);

                var mockContext = new Mock <LazyInternalContext>(
                    new MockHistoryContext(), new Mock <IInternalConnection>().Object, null, null, null, null, null)
                {
                    CallBase = true
                };
                mockContext.Object.ModelProviderInfo = ProviderRegistry.Sql2008_ProviderInfo;

                var model = LazyInternalContext.CreateModel(mockContext.Object);

                Assert.NotSame(dbCompiledModelInStore, model);

                store.Verify(c => c.TryLoad(It.IsAny <Type>()), Times.Never(),
                             "should not call store for HistoryContext");

                store.Verify(c => c.Save(It.IsAny <Type>(), It.IsAny <DbModel>()), Times.Never(),
                             "should not call store for HistoryContext");
            }
            finally //clean up
            {
                MutableResolver.ClearResolvers();
            }
        }
Ejemplo n.º 13
0
        public DbModelBuilder CreateModelBuilder()
        {
            DbModelBuilderVersionAttribute versionAttribute = this._attributeProvider.GetAttributes(this.Owner.GetType()).OfType <DbModelBuilderVersionAttribute>().FirstOrDefault <DbModelBuilderVersionAttribute>();
            DbModelBuilder modelBuilder   = new DbModelBuilder(versionAttribute != null ? versionAttribute.Version : DbModelBuilderVersion.Latest);
            string         modelNamespace = LazyInternalContext.StripInvalidCharacters(this.Owner.GetType().Namespace);

            if (!string.IsNullOrWhiteSpace(modelNamespace))
            {
                modelBuilder.Conventions.Add((IConvention) new ModelNamespaceConvention(modelNamespace));
            }
            string containerName = LazyInternalContext.StripInvalidCharacters(this.Owner.GetType().Name);

            if (!string.IsNullOrWhiteSpace(containerName))
            {
                modelBuilder.Conventions.Add((IConvention) new ModelContainerConvention(containerName));
            }
            new DbSetDiscoveryService(this.Owner).RegisterSets(modelBuilder);
            this.Owner.CallOnModelCreating(modelBuilder);
            if (this.OnModelCreating != null)
            {
                this.OnModelCreating(modelBuilder);
            }
            return(modelBuilder);
        }
        public void Dispose_calls_EntityConnection_dispose_before_InternalConnection_dispose()
        {
            var results = new List<string>();

            var underlyingConnection = new Mock<DbConnection>();
            
            var lazyInternalConnectionMock = new Mock<LazyInternalConnection>("fake");
            lazyInternalConnectionMock.SetupGet(ic => ic.Connection).Returns(underlyingConnection.Object);
            lazyInternalConnectionMock.Setup(ic => ic.Dispose()).Callback(() => results.Add("LazyInternalConnection Dispose() called"));

            var metadataWorkspaceMock = new Mock<MetadataWorkspace>();
            metadataWorkspaceMock.Setup(mw => mw.GetItemCollection(DataSpace.CSSpace)).Returns(() => null);
            
            var dbContext = new TestDbContext();

            var entityConnectionMock = new Mock<EntityConnection>();
            entityConnectionMock.SetupGet(ec => ec.ConnectionString).Returns("fake");
            entityConnectionMock.Setup(ec => ec.GetMetadataWorkspace()).Returns(metadataWorkspaceMock.Object);
            entityConnectionMock.Protected().Setup("Dispose", ItExpr.IsAny<bool>()).
                Callback<bool>(b => results.Add("EntityConnection Dispose() called"));

            var objectContextMock = new Mock<ObjectContext>(entityConnectionMock.Object, true)
            {
                CallBase = true
            };
            objectContextMock.SetupGet(oc => oc.MetadataWorkspace).Returns(metadataWorkspaceMock.Object);

            var lazyInternalContext = new LazyInternalContext(
                dbContext, lazyInternalConnectionMock.Object, null, null, null, null, objectContextMock.Object);
            
            lazyInternalContext.DisposeContext(true);

            Assert.Equal(2, results.Count);
            Assert.Same("EntityConnection Dispose() called", results[0]);
            Assert.Same("LazyInternalConnection Dispose() called", results[1]);
        }
        /// <summary>
        ///     Creates an immutable, cacheable representation of the model defined by this builder.
        ///     This model can be used to create an <see cref="ObjectContext" /> or can be passed to a <see cref="DbContext" />
        ///     constructor to create a <see cref="DbContext" /> for this model.
        /// </summary>
        public static DbCompiledModel CreateModel(LazyInternalContext internalContext)
        {
            var modelBuilder = internalContext.CreateModelBuilder();

            var model
                = (internalContext._modelProviderInfo == null)
                      ? modelBuilder.Build(internalContext._internalConnection.Connection)
                      : modelBuilder.Build(internalContext._modelProviderInfo);

            return model.Compile();
        }
Ejemplo n.º 16
0
        // <summary>
        // Creates an immutable, cacheable representation of the model defined by this builder.
        // This model can be used to create an <see cref="ObjectContext" /> or can be passed to a <see cref="DbContext" />
        // constructor to create a <see cref="DbContext" /> for this model.
        // </summary>
        public static DbCompiledModel CreateModel(LazyInternalContext internalContext)
        {
            var contextType = internalContext.Owner.GetType();

            DbModelStore modelStore = null;
            if (!(internalContext.Owner is HistoryContext))
            {
                modelStore = DbConfiguration.DependencyResolver.GetService<DbModelStore>();
                if (modelStore != null)
                {
                    var compiledModel = modelStore.TryLoad(contextType);
                    if (compiledModel != null)
                    {
                        return compiledModel;
                    }
                }
            }

            var modelBuilder = internalContext.CreateModelBuilder();

            var model
                = (internalContext._modelProviderInfo == null)
                      ? modelBuilder.Build(internalContext._internalConnection.Connection)
                      : modelBuilder.Build(internalContext._modelProviderInfo);

            internalContext._modelBeingInitialized = model;

            if (modelStore != null)
            {
                modelStore.Save(contextType, model);
            }

            return model.Compile();
        }