public GlimpseDbProviderServices(DbProviderServices innerProviderServices) { InnerProviderServices = innerProviderServices; #if (EF5 && NET45) || EF6 setParameterValueMethod = InnerProviderServices.GetType().GetMethod("SetParameterValue", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); #endif }
private void InitializeProviderServices(string providerManifestToken) { using (var connection = CreateConnection()) { _providerServices = DbProviderServices.GetProviderServices(connection); _providerManifest = _providerServices.GetProviderManifest(providerManifestToken); } }
/// <summary> /// Initializes a new instance of the <see cref="DbProviderServicesProxy"/> class. /// </summary> /// <param name="services">The services.</param> /// <param name="policy">The policy.</param> /// <param name="cache">The cache.</param> /// <param name="txHandler">Transaction handler.</param> public DbProviderServicesProxy(DbProviderServices services, IDbCachingPolicy policy, DbCache cache, DbTransactionInterceptor txHandler) { Debug.Assert(services != null); Debug.Assert(cache != null); Debug.Assert(txHandler != null); var proxy = services as DbProviderServicesProxy; _services = proxy != null ? proxy._services : services; _policy = policy ?? DefaultPolicy; _cache = cache; _txHandler = txHandler; }
// <summary> // Updates storeParameter size, precision and scale properties from user provided parameter properties. // </summary> private static void SyncParameterProperties( EntityParameter entityParameter, DbParameter storeParameter, DbProviderServices storeProviderServices) { IDbDataParameter dbDataParameter = storeParameter; // DBType is not currently syncable; it's part of the cache key anyway; this is because we can't guarantee // that the store provider will honor it -- (SqlClient doesn't...) //if (entityParameter.IsDbTypeSpecified) //{ // storeParameter.DbType = entityParameter.DbType; //} // Give the store provider the opportunity to set the value before any parameter state has been copied from // the EntityParameter. var parameterTypeUsage = TypeHelpers.GetPrimitiveTypeUsageForScalar(entityParameter.GetTypeUsage()); storeProviderServices.SetParameterValue(storeParameter, parameterTypeUsage, entityParameter.Value); // Override the store provider parameter state with any explicitly specified values from the EntityParameter. if (entityParameter.IsDirectionSpecified) { storeParameter.Direction = entityParameter.Direction; } if (entityParameter.IsIsNullableSpecified) { storeParameter.IsNullable = entityParameter.IsNullable; } if (entityParameter.IsSizeSpecified) { storeParameter.Size = entityParameter.Size; } if (entityParameter.IsPrecisionSpecified) { dbDataParameter.Precision = entityParameter.Precision; } if (entityParameter.IsScaleSpecified) { dbDataParameter.Scale = entityParameter.Scale; } }
internal static async Task <ShapelessBufferedDataRecord> InitializeAsync( string providerManifestToken, DbProviderServices providerSerivces, DbDataReader reader, CancellationToken cancellationToken) { var record = new ShapelessBufferedDataRecord(); record.ReadMetadata(providerManifestToken, providerSerivces, reader); var fieldCount = record.FieldCount; var resultSet = new List <object[]>(); while (await reader.ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { var row = new object[fieldCount]; for (var i = 0; i < fieldCount; i++) { if (await reader.IsDBNullAsync(i, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { row[i] = DBNull.Value; } else if (record._spatialDataReader != null && record._geographyColumns[i]) { row[i] = await record._spatialDataReader.GetGeographyAsync(i, cancellationToken) .ConfigureAwait(continueOnCapturedContext: false); } else if (record._spatialDataReader != null && record._geometryColumns[i]) { row[i] = await record._spatialDataReader.GetGeometryAsync(i, cancellationToken) .ConfigureAwait(continueOnCapturedContext: false); } else { row[i] = await reader.GetFieldValueAsync <object>(i, cancellationToken) .ConfigureAwait(continueOnCapturedContext: false); } } resultSet.Add(row); } record._rowCount = resultSet.Count; record._resultSet = resultSet; return(record); }
internal async Task InitializeAsync( string providerManifestToken, DbProviderServices providerSerivces, Type[] columnTypes, bool[] nullableColumns, CancellationToken cancellationToken) { if (this._underlyingReader == null) { return; } cancellationToken.ThrowIfCancellationRequested(); DbDataReader reader = this._underlyingReader; this._underlyingReader = (DbDataReader)null; try { if (columnTypes != null && reader.GetType().Name != "SqlDataReader") { this._bufferedDataRecords.Add(await ShapedBufferedDataRecord.InitializeAsync(providerManifestToken, providerSerivces, reader, columnTypes, nullableColumns, cancellationToken).WithCurrentCulture <BufferedDataRecord>()); } else { this._bufferedDataRecords.Add((BufferedDataRecord)await ShapelessBufferedDataRecord.InitializeAsync(providerManifestToken, providerSerivces, reader, cancellationToken).WithCurrentCulture <ShapelessBufferedDataRecord>()); } while (true) { if (await reader.NextResultAsync(cancellationToken).WithCurrentCulture <bool>()) { this._bufferedDataRecords.Add((BufferedDataRecord)await ShapelessBufferedDataRecord.InitializeAsync(providerManifestToken, providerSerivces, reader, cancellationToken).WithCurrentCulture <ShapelessBufferedDataRecord>()); } else { break; } } this._recordsAffected = reader.RecordsAffected; this._currentResultSet = this._bufferedDataRecords[this._currentResultSetNumber]; } finally { reader.Dispose(); } }
/// <summary> /// Another method, can pass in the MetadataCacheKey /// </summary> /// <typeparam name="T">the object context.</typeparam> /// <param name="connection">The connection.</param> /// <param name="cacheKey">The cache Key.</param> /// <returns>the context type</returns> public static T CreateObjectContext <T>(this DbConnection connection, MetadataCacheKey cacheKey) where T : System.Data.Objects.ObjectContext { var workspace = MetadataCache.GetWorkspace(cacheKey); var factory = DbProviderServices.GetProviderFactory(connection); var itemCollection = workspace.GetItemCollection(DataSpace.SSpace); var fieldInfo = itemCollection.GetType().GetField( "_providerFactory", // <==== big fat ugly hack BindingFlags.NonPublic | BindingFlags.Instance); if (fieldInfo != null) { fieldInfo.SetValue(itemCollection, factory); } var ec = new EntityConnection(workspace, connection); return(CtorCache <T, EntityConnection> .Ctor(ec)); }
private ObjectResult <T> GetResults(MergeOption?forMergeOption) { QueryState.ObjectContext.AsyncMonitor.EnsureNotEntered(); var executionStrategy = DbProviderServices.GetExecutionStrategy( QueryState.ObjectContext.Connection, QueryState.ObjectContext.MetadataWorkspace); if (executionStrategy.RetriesOnFailure && QueryState.EffectiveStreamingBehaviour) { throw new InvalidOperationException(Strings.ExecutionStrategy_StreamingNotSupported); } return(executionStrategy.Execute( () => QueryState.ObjectContext.ExecuteInTransaction( () => QueryState.GetExecutionPlan(forMergeOption) .Execute <T>(QueryState.ObjectContext, QueryState.Parameters), throwOnExistingTransaction: executionStrategy.RetriesOnFailure, startLocalTransaction: false, releaseConnectionOnSuccess: !QueryState.EffectiveStreamingBehaviour))); }
public override string GenerateProcedureBody(ICollection <DbModificationCommandTree> commandTrees, string rowsAffectedParameter, string providerManifestToken) { MySqlConnection con = new MySqlConnection(); MigrationStatement stmt = new MigrationStatement(); _providerManifest = DbProviderServices.GetProviderServices(con).GetProviderManifest(providerManifestToken); var cmdStr = ""; SqlGenerator generator = new SelectGenerator(); foreach (var commandTree in commandTrees) { switch (commandTree.CommandTreeKind) { case DbCommandTreeKind.Insert: generator = new InsertGenerator(); cmdStr = generator.GenerateSQL(commandTree); break; case DbCommandTreeKind.Delete: generator = new DeleteGenerator(); cmdStr = generator.GenerateSQL(commandTree); break; case DbCommandTreeKind.Update: generator = new UpdateGenerator(); cmdStr = generator.GenerateSQL(commandTree); break; case DbCommandTreeKind.Query: generator = new SelectGenerator(); cmdStr = generator.GenerateSQL(commandTree); break; case DbCommandTreeKind.Function: generator = new FunctionGenerator(); cmdStr = generator.GenerateSQL(commandTree); break; } stmt.Sql += cmdStr.Replace("dbo.", "") + ";"; } return(stmt.Sql); }
internal static Task <BufferedDataRecord> InitializeAsync( string providerManifestToken, DbProviderServices providerServices, DbDataReader reader, Type[] columnTypes, bool[] nullableColumns, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var record = new ShapedBufferedDataRecord(); record.ReadMetadata(providerManifestToken, providerServices, reader); DbSpatialDataReader spatialDataReader = null; if (columnTypes.Any(t => t == typeof(DbGeography) || t == typeof(DbGeometry))) { spatialDataReader = providerServices.GetSpatialDataReader(reader, providerManifestToken); } return(record.InitializeAsync(reader, spatialDataReader, columnTypes, nullableColumns, cancellationToken)); }
/// <summary> /// Main driver function. /// </summary> /// <param name="args"></param> public static void Generate(string outputFileName) { //The following functions are omitted because they have counterparts in the BCL string[] omittedFunctions = new[] { "Sum", "Min", "Max", "Average", "Avg", "Count", "BigCount", "Trim", "RTrim", "LTrim", "Concat", "Length", "Substring", "Replace", "IndexOf", "ToUpper", "ToLower", "Contains", "StartsWith", "EndsWith", "Year", "Month", "Day", "DayOfYear", "Hour", "Minute", "Second", "Millisecond", "CurrentDateTime", "CurrentDateTimeOffset", "CurrentUtcDateTime", "BitwiseAnd", "BitwiseOr", "BitwiseXor", "BitwiseNot", "Round", "Abs", "Power", "NewGuid", "Floor", "Ceiling", }; //The following functions are omitted from SqlFunctions because they already exist in EntityFunctions string[] omittedSqlFunctions = new[] { "STDEV", "STDEVP", "VAR", "VARP", "COUNT_BIG", "Left", "Right", "Reverse", "GetTotalOffsetMinutes", "TruncateTime", "CreateDateTime", "CreateDateTimeOffset", "CreateTime", "Add", "Diff", "Truncate", "SYSDATETIME", "SYSUTCDATETIME", "SYSDATETIMEOFFSET", "LEN", "LOWER", "UPPER", "NEWID", }; DbProviderServices dbProviderServices = (DbProviderServices)((IServiceProvider)JetProviderFactory.Instance).GetService(typeof(DbProviderServices)); DbProviderManifest dbProviderManifest = dbProviderServices.GetProviderManifest("Jet"); var storeFunctions = dbProviderManifest.GetStoreFunctions(); IEnumerable <EdmFunction> sqlFunctions = storeFunctions .Where(f => f.NamespaceName == "Jet") .Where(f => !(omittedFunctions.Concat(omittedSqlFunctions)).Contains(f.Name, StringComparer.OrdinalIgnoreCase)); FunctionStubFileWriter sqlStubsFileWriter = new FunctionStubFileWriter(sqlFunctions, GetFunctionNamingDictionary(), GetParameterNamingDictionary()); sqlStubsFileWriter.GenerateToFile(outputFileName, "JetEntityFrameworkProvider", "JetFunctions", "Jet", true); }
private HistoryRepository SetupHistoryRepositoryForOrderingTest() { ResetDatabase(); using (var context = CreateContext <ShopContext_v1>()) { var model = new VersionedModel(context.GetModel()); var clonedConnection = DbProviderServices.GetProviderFactory(context.Database.Connection).CreateConnection(); clonedConnection.ConnectionString = context.Database.Connection.ConnectionString; using (var historyContext = new HistoryContext(clonedConnection, defaultSchema: null)) { context.InternalContext.MarkDatabaseInitialized(); context.Database.ExecuteSqlCommand( ((IObjectContextAdapter)historyContext).ObjectContext.CreateDatabaseScript()); historyContext.History.Add( new HistoryRow { MigrationId = "227309030010001_Migration1", ContextKey = "MyKey", Model = new ModelCompressor().Compress(model.Model), ProductVersion = "", }); historyContext.History.Add( new HistoryRow { MigrationId = "227209030010001_Migration2", ContextKey = "MyKey", Model = new ModelCompressor().Compress(model.Model), ProductVersion = "", }); historyContext.SaveChanges(); } } return(new HistoryRepository(Mock.Of <InternalContextForMock>(), ConnectionString, ProviderFactory, "MyKey", null, HistoryContext.DefaultFactory)); }
public static string GetProviderManifestTokenChecked( this DbProviderServices providerServices, DbConnection connection) { DebugCheck.NotNull(providerServices); DebugCheck.NotNull(connection); try { return(providerServices.GetProviderManifestToken(connection)); } catch (ProviderIncompatibleException ex) { if ("(localdb)\v11.0".Equals(connection.DataSource, StringComparison.OrdinalIgnoreCase)) { throw new ProviderIncompatibleException(Strings.BadLocalDBDatabaseName, ex); } throw new ProviderIncompatibleException(Strings.FailedToGetProviderInformation, ex); } }
protected virtual void ReadMetadata(string providerManifestToken, DbProviderServices providerServices, DbDataReader reader) { var fieldCount = reader.FieldCount; var dataTypeNames = new string[fieldCount]; var columnTypes = new Type[fieldCount]; var columnNames = new string[fieldCount]; for (var i = 0; i < fieldCount; i++) { dataTypeNames[i] = reader.GetDataTypeName(i); columnTypes[i] = reader.GetFieldType(i); columnNames[i] = reader.GetName(i); } _dataTypeNames = dataTypeNames; _fieldTypes = columnTypes; _columnNames = columnNames; _fieldNameLookup = new Lazy <FieldNameLookup>( () => new FieldNameLookup(new ReadOnlyCollection <string>(columnNames)), isThreadSafe: false); }
internal virtual ObjectResult <TResultType> Execute <TResultType>( ObjectContext context, ObjectParameterCollection parameterValues) { DbDataReader reader = (DbDataReader)null; BufferedDataReader bufferedDataReader = (BufferedDataReader)null; try { using (EntityCommand entityCommand = this.PrepareEntityCommand(context, parameterValues)) reader = entityCommand.GetCommandDefinition().ExecuteStoreCommands(entityCommand, this.Streaming ? CommandBehavior.Default : CommandBehavior.SequentialAccess); ShaperFactory <TResultType> resultShaperFactory = (ShaperFactory <TResultType>) this.ResultShaperFactory; Shaper <TResultType> shaper; if (this.Streaming) { shaper = resultShaperFactory.Create(reader, context, context.MetadataWorkspace, this.MergeOption, true, this.Streaming); } else { StoreItemCollection itemCollection = (StoreItemCollection)context.MetadataWorkspace.GetItemCollection(DataSpace.SSpace); DbProviderServices service = DbConfiguration.DependencyResolver.GetService <DbProviderServices>((object)itemCollection.ProviderInvariantName); bufferedDataReader = new BufferedDataReader(reader); bufferedDataReader.Initialize(itemCollection.ProviderManifestToken, service, resultShaperFactory.ColumnTypes, resultShaperFactory.NullableColumns); shaper = resultShaperFactory.Create((DbDataReader)bufferedDataReader, context, context.MetadataWorkspace, this.MergeOption, true, this.Streaming); } TypeUsage resultItemType = this.ResultType.EdmType.BuiltInTypeKind != BuiltInTypeKind.CollectionType ? this.ResultType : ((CollectionType)this.ResultType.EdmType).TypeUsage; return(new ObjectResult <TResultType>(shaper, this._singleEntitySet, resultItemType)); } catch (Exception ex) { if (this.Streaming && reader != null) { reader.Dispose(); } if (!this.Streaming && bufferedDataReader != null) { bufferedDataReader.Dispose(); } throw; } }
public virtual bool Exists(DbConnection connection, int?commandTimeout, Lazy <StoreItemCollection> storeItemCollection) { DebugCheck.NotNull(connection); if (connection.State == ConnectionState.Open) { return(true); } try { return(DbProviderServices.GetProviderServices(connection) .DatabaseExists(connection, commandTimeout, storeItemCollection)); } catch { // In situations where the user does not have access to the master database // the above DatabaseExists call fails and throws an exception. Rather than // just let that exception escape to the caller we instead try a different // approach to see if the database really does exist or not. The approach // is to try to open a connection to the database. If this succeeds then // we know that the database exists. If it fails then the database may // not exist or there may be some other issue connecting to it. In either // case for the purpose of this call we assume that it does not exist and // return false since this functionally gives the best experience in most // scenarios. try { connection.Open(); return(true); } catch (Exception) { return(false); } finally { connection.Close(); } } }
protected virtual void ReadMetadata( string providerManifestToken, DbProviderServices providerServices, DbDataReader reader) { int fieldCount = reader.FieldCount; string[] strArray = new string[fieldCount]; Type[] typeArray = new Type[fieldCount]; string[] columnNames = new string[fieldCount]; for (int ordinal = 0; ordinal < fieldCount; ++ordinal) { strArray[ordinal] = reader.GetDataTypeName(ordinal); typeArray[ordinal] = reader.GetFieldType(ordinal); columnNames[ordinal] = reader.GetName(ordinal); } this._dataTypeNames = strArray; this._fieldTypes = typeArray; this._columnNames = columnNames; this._fieldNameLookup = new Lazy <FieldNameLookup>((Func <FieldNameLookup>)(() => new FieldNameLookup(new ReadOnlyCollection <string>((IList <string>)columnNames))), false); }
/// <summary> /// Converts a set of migration operations into Microsoft SQL Server specific SQL. /// </summary> /// <param name="migrationOperations"> The operations to be converted. </param> /// <param name="providerManifestToken"> Token representing the version of SQL Server being targeted (i.e. "2005", "2008"). </param> /// <returns> A list of SQL statements to be executed to perform the migration operations. </returns> public override IEnumerable <MigrationStatement> Generate( IEnumerable <MigrationOperation> migrationOperations, string providerManifestToken) { Check.NotNull(migrationOperations, "migrationOperations"); Check.NotNull(providerManifestToken, "providerManifestToken"); _statements = new List <MigrationStatement>(); _generatedSchemas = new HashSet <string>(); _variableCounter = 0; using (var connection = CreateConnection()) { _providerManifest = DbProviderServices.GetProviderServices(connection) .GetProviderManifest(providerManifestToken); } migrationOperations.Each <dynamic>(o => Generate(o)); return(_statements); }
public override IEnumerable <MigrationStatement> Generate(IEnumerable <MigrationOperation> migrationOperations, string providerManifestToken) { MySqlConnection con = new MySqlConnection(); List <MigrationStatement> stmts = new List <MigrationStatement>(); _providerManifest = DbProviderServices.GetProviderServices(con).GetProviderManifest(providerManifestToken); foreach (MigrationOperation op in migrationOperations) { OpDispatcher opdis = _dispatcher[op.GetType().Name]; stmts.Add(opdis(op)); } if (_specialStmts.Count > 0) { foreach (var item in _specialStmts) { stmts.Add(item); } } return(stmts); }
private static string GetProviderInvariantName(DbConnection connection) { var type = DbProviderServices.GetProviderFactory(connection).GetType(); var assemblyName = new AssemblyName(type.Assembly.FullName); foreach (DataRow providerRow in (InternalDataCollectionBase)DbProviderFactories.GetFactoryClasses().Rows) { var typeName = (string)providerRow[3]; var rowProviderFactoryAssemblyName = (AssemblyName)null; Type.GetType( typeName, a => { rowProviderFactoryAssemblyName = a; return((Assembly)null); }, (assembly, str, b) => (Type)null); if (rowProviderFactoryAssemblyName == null) { continue; } if (!string.Equals( assemblyName.Name, rowProviderFactoryAssemblyName.Name, StringComparison.OrdinalIgnoreCase)) { continue; } if (DbProviderFactories.GetFactory(providerRow).GetType() == type) { return((string)providerRow[2]); } } throw new Exception("Couldn't get the provider invariant name"); }
public void DatabaseExists_uses_ExecutionStrategy() { var executionStrategyMock = new Mock <IExecutionStrategy>(); executionStrategyMock.Setup(m => m.Execute(It.IsAny <Action>())).Callback <Action>(a => a()); MutableResolver.AddResolver <Func <IExecutionStrategy> >(key => (Func <IExecutionStrategy>)(() => executionStrategyMock.Object)); try { var connection = new SqlConnection(SimpleConnectionString(("master"))); Assert.True( DbProviderServices.GetProviderServices(connection).DatabaseExists( connection, null, new Mock <StoreItemCollection>().Object)); } finally { MutableResolver.ClearResolvers(); } executionStrategyMock.Verify(m => m.Execute(It.IsAny <Action>()), Times.Once()); }
private static DbProviderServices GetInstance(Type providerType) { MemberInfo memberInfo1 = (MemberInfo)providerType.GetStaticProperty("Instance"); if ((object)memberInfo1 == null) { memberInfo1 = (MemberInfo)providerType.GetField("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } MemberInfo memberInfo2 = memberInfo1; if (memberInfo2 == (MemberInfo)null) { throw new InvalidOperationException(Strings.EF6Providers_InstanceMissing((object)providerType.AssemblyQualifiedName)); } DbProviderServices providerServices = memberInfo2.GetValue() as DbProviderServices; if (providerServices == null) { throw new InvalidOperationException(Strings.EF6Providers_NotDbProviderServices((object)providerType.AssemblyQualifiedName)); } return(providerServices); }
public override IEnumerable <MigrationStatement> Generate(IEnumerable <MigrationOperation> migrationOperations, string providerManifestToken) { MySqlConnection con = new MySqlConnection(); List <MigrationStatement> stmts = new List <MigrationStatement>(); _providerManifestToken = providerManifestToken; _providerManifest = DbProviderServices.GetProviderServices(con).GetProviderManifest(providerManifestToken); //verify if there is one or more add/alter column operation, if there is then look for primary key operations. Alter in case that the user wants to change the current PK column if ((from cols in migrationOperations.OfType <AddColumnOperation>() select cols).Count() > 0 || (from cols in migrationOperations.OfType <AlterColumnOperation>() select cols).Count() > 0) { _pkOperations = (from pks in migrationOperations.OfType <AddPrimaryKeyOperation>() select pks).ToList(); } foreach (MigrationOperation op in migrationOperations) { if (!_dispatcher.ContainsKey(op.GetType().Name)) { throw new NotImplementedException(op.GetType().Name); } OpDispatcher opdis = _dispatcher[op.GetType().Name]; var item = opdis(op); if (item != null) { stmts.Add(item); } } if (_specialStmts.Count > 0) { foreach (var item in _specialStmts) { if (item != null) { stmts.Add(item); } } } return(stmts); }
private static ReaderMetadata ReadMetadata(string providerManifestToken, DbProviderServices providerSerivces, DbDataReader reader) { var fieldCount = reader.FieldCount; var hasSpatialColumns = false; DbSpatialDataReader spatialDataReader = null; bool[] geographyColumns = null; bool[] geometryColumns = null; try { spatialDataReader = providerSerivces.GetSpatialDataReader(reader, providerManifestToken); geographyColumns = new bool[fieldCount]; geometryColumns = new bool[fieldCount]; } catch (ProviderIncompatibleException) { } var dataTypeNames = new string[fieldCount]; var columnTypes = new Type[fieldCount]; var columnNames = new string[fieldCount]; for (var i = 0; i < fieldCount; i++) { dataTypeNames[i] = reader.GetDataTypeName(i); columnTypes[i] = reader.GetFieldType(i); columnNames[i] = reader.GetName(i); if (spatialDataReader != null) { geographyColumns[i] = spatialDataReader.IsGeographyColumn(i); geometryColumns[i] = spatialDataReader.IsGeometryColumn(i); hasSpatialColumns = hasSpatialColumns || geographyColumns[i] || geometryColumns[i]; Debug.Assert(!geographyColumns[i] || !geometryColumns[i]); } } return(new ReaderMetadata( fieldCount, dataTypeNames, columnTypes, columnNames, hasSpatialColumns, spatialDataReader, geographyColumns, geometryColumns)); }
/// <summary> /// Initializes a new instance of the <see cref="EntityFrameworkConfig{TContext}"/> class. This class sets up the database configuration for Entity Framework. /// </summary> /// <param name="dbConnectionFactory">The database connection factory.</param> /// <param name="providerInvariantName">The invariant provider name.</param> /// <param name="dbProviderFactory">The database provider factory.</param> /// <param name="dbProviderServices">The database provider services.</param> /// <param name="databaseInitializer">The database initializer.</param> public EntityFrameworkConfig( IDbConnectionFactory dbConnectionFactory, string providerInvariantName, DbProviderFactory dbProviderFactory, DbProviderServices dbProviderServices, IDatabaseInitializer <TContext> databaseInitializer) : base() { if (dbConnectionFactory == null) { throw new ArgumentNullException("dbConnectionFactory"); } if (string.IsNullOrWhiteSpace(providerInvariantName)) { throw new ArgumentNullException("providerInvariantName"); } if (dbProviderFactory == null) { throw new ArgumentNullException("dbProviderFactory"); } if (dbProviderServices == null) { throw new ArgumentNullException("dbProviderServices"); } if (databaseInitializer == null) { throw new ArgumentNullException("databaseInitializer"); } this.SetDefaultConnectionFactory(dbConnectionFactory); this.SetProviderFactory(providerInvariantName, dbProviderFactory); this.SetProviderServices(providerInvariantName, dbProviderServices); this.SetDatabaseInitializer(databaseInitializer); }
internal virtual string GetProviderServicesInternal(string invariantName) { DebugCheck.NotEmpty(invariantName); DbConfiguration.LoadConfiguration(_assembly); var dependencyResolver = DbConfiguration.DependencyResolver; DbProviderServices providerServices = null; try { providerServices = dependencyResolver.GetService <DbProviderServices>(invariantName); } catch { } if (providerServices == null) { return(null); } return(providerServices.GetType().AssemblyQualifiedName); }
internal static ShapelessBufferedDataRecord Initialize( string providerManifestToken, DbProviderServices providerSerivces, DbDataReader reader) { ShapelessBufferedDataRecord bufferedDataRecord = new ShapelessBufferedDataRecord(); bufferedDataRecord.ReadMetadata(providerManifestToken, providerSerivces, reader); int fieldCount = bufferedDataRecord.FieldCount; List <object[]> objArrayList = new List <object[]>(); if (bufferedDataRecord._spatialDataReader != null) { while (reader.Read()) { object[] objArray = new object[fieldCount]; for (int ordinal = 0; ordinal < fieldCount; ++ordinal) { objArray[ordinal] = !reader.IsDBNull(ordinal) ? (!bufferedDataRecord._geographyColumns[ordinal] ? (!bufferedDataRecord._geometryColumns[ordinal] ? reader.GetValue(ordinal) : (object)bufferedDataRecord._spatialDataReader.GetGeometry(ordinal)) : (object)bufferedDataRecord._spatialDataReader.GetGeography(ordinal)) : (object)DBNull.Value; } objArrayList.Add(objArray); } } else { while (reader.Read()) { object[] values = new object[fieldCount]; reader.GetValues(values); objArrayList.Add(values); } } bufferedDataRecord._rowCount = objArrayList.Count; bufferedDataRecord._resultSet = objArrayList; return(bufferedDataRecord); }
private static EdmItemCollection LoadEdmItemCollection(string csdlName) { Debug.Assert(!string.IsNullOrWhiteSpace(csdlName), "csdlName cannot be null or empty"); using (var csdlReader = DbProviderServices.GetConceptualSchemaDefinition(csdlName)) { IList <EdmSchemaError> errors; var edmItemCollection = EdmItemCollection.Create( new[] { csdlReader }, new ReadOnlyCollection <string>( new List <string> { GetProviderServicesInformationLocationPath( typeof(DbProviderServices).Assembly.FullName, csdlName) }), out errors); Debug.Assert( errors == null || errors.Count == 0, "Unexpected errors conceptual schema definition csdl"); return(edmItemCollection); } }
internal void Initialize( string providerManifestToken, DbProviderServices providerServices, Type[] columnTypes, bool[] nullableColumns) { var reader = _underlyingReader; if (reader == null) { return; } _underlyingReader = null; try { if (columnTypes != null && reader.GetType().Name != "SqlDataReader") { _bufferedDataRecords.Add( ShapedBufferedDataRecord.Initialize(providerManifestToken, providerServices, reader, columnTypes, nullableColumns)); } else { _bufferedDataRecords.Add(ShapelessBufferedDataRecord.Initialize(providerManifestToken, providerServices, reader)); } while (reader.NextResult()) { _bufferedDataRecords.Add(ShapelessBufferedDataRecord.Initialize(providerManifestToken, providerServices, reader)); } _recordsAffected = reader.RecordsAffected; _currentResultSet = _bufferedDataRecords[_currentResultSetNumber]; } finally { reader.Dispose(); } }
public GlimpseDbProviderServices(DbProviderServices innerProviderServices) { InnerProviderServices = innerProviderServices; }
internal EntityCommandDefinition( DbProviderFactory storeProviderFactory, DbCommandTree commandTree, IDbDependencyResolver resolver = null, BridgeDataReaderFactory bridgeDataReaderFactory = null, ColumnMapFactory columnMapFactory = null) { DebugCheck.NotNull(storeProviderFactory); DebugCheck.NotNull(commandTree); _bridgeDataReaderFactory = bridgeDataReaderFactory ?? new BridgeDataReaderFactory(); _columnMapFactory = columnMapFactory ?? new ColumnMapFactory(); _storeProviderServices = (resolver != null ? resolver.GetService <DbProviderServices>(storeProviderFactory.GetProviderInvariantName()) : null) ?? storeProviderFactory.GetProviderServices(); try { if (DbCommandTreeKind.Query == commandTree.CommandTreeKind) { // Next compile the plan for the command tree var mappedCommandList = new List <ProviderCommandInfo>(); ColumnMap columnMap; int columnCount; PlanCompiler.Compile(commandTree, out mappedCommandList, out columnMap, out columnCount, out _entitySets); _columnMapGenerators = new IColumnMapGenerator[] { new ConstantColumnMapGenerator(columnMap, columnCount) }; // Note: we presume that the first item in the ProviderCommandInfo is the root node; Debug.Assert(mappedCommandList.Count > 0, "empty providerCommandInfo collection and no exception?"); // this shouldn't ever happen. // Then, generate the store commands from the resulting command tree(s) _mappedCommandDefinitions = new List <DbCommandDefinition>(mappedCommandList.Count); foreach (var providerCommandInfo in mappedCommandList) { var providerCommandDefinition = _storeProviderServices.CreateCommandDefinition(providerCommandInfo.CommandTree); if (null == providerCommandDefinition) { throw new ProviderIncompatibleException(Strings.ProviderReturnedNullForCreateCommandDefinition); } _mappedCommandDefinitions.Add(providerCommandDefinition); } } else { Debug.Assert( DbCommandTreeKind.Function == commandTree.CommandTreeKind, "only query and function command trees are supported"); var entityCommandTree = (DbFunctionCommandTree)commandTree; // Retrieve mapping and metadata information for the function import. var mapping = GetTargetFunctionMapping(entityCommandTree); IList <FunctionParameter> returnParameters = entityCommandTree.EdmFunction.ReturnParameters; var resultSetCount = returnParameters.Count > 1 ? returnParameters.Count : 1; _columnMapGenerators = new IColumnMapGenerator[resultSetCount]; var storeResultType = DetermineStoreResultType(mapping, 0, out _columnMapGenerators[0]); for (var i = 1; i < resultSetCount; i++) { DetermineStoreResultType(mapping, i, out _columnMapGenerators[i]); } // Copy over parameters (this happens through a more indirect route in the plan compiler, but // it happens nonetheless) var providerParameters = new List <KeyValuePair <string, TypeUsage> >(); foreach (var parameter in entityCommandTree.Parameters) { providerParameters.Add(parameter); } // Construct store command tree usage. var providerCommandTree = new DbFunctionCommandTree( entityCommandTree.MetadataWorkspace, DataSpace.SSpace, mapping.TargetFunction, storeResultType, providerParameters); var storeCommandDefinition = _storeProviderServices.CreateCommandDefinition(providerCommandTree); _mappedCommandDefinitions = new List <DbCommandDefinition>(1) { storeCommandDefinition }; var firstResultEntitySet = mapping.FunctionImport.EntitySets.FirstOrDefault(); if (firstResultEntitySet != null) { _entitySets = new Set <EntitySet>(); _entitySets.Add(mapping.FunctionImport.EntitySets.FirstOrDefault()); _entitySets.MakeReadOnly(); } } // Finally, build a list of the parameters that the resulting command should have; var parameterList = new List <EntityParameter>(); foreach (var queryParameter in commandTree.Parameters) { var parameter = CreateEntityParameterFromQueryParameter(queryParameter); parameterList.Add(parameter); } _parameters = new ReadOnlyCollection <EntityParameter>(parameterList); } catch (EntityCommandCompilationException) { // No need to re-wrap EntityCommandCompilationException throw; } catch (Exception e) { // we should not be wrapping all exceptions if (e.IsCatchableExceptionType()) { // we don't wan't folks to have to know all the various types of exceptions that can // occur, so we just rethrow a CommandDefinitionException and make whatever we caught // the inner exception of it. throw new EntityCommandCompilationException(Strings.EntityClient_CommandDefinitionPreparationFailed, e); } throw; } }
public CachingProviderServices(DbProviderServices providerServices, CacheTransactionHandler cacheTransactionHandler, CachingPolicy cachingPolicy = null) { _providerServices = providerServices; _cacheTransactionHandler = cacheTransactionHandler; _cachingPolicy = cachingPolicy ?? new CachingPolicy(); }
public DbProviderServicesEx(DbProviderServices inner, IAopFilter appender) { this.inner = inner; this.appender = appender; }
/// <summary> /// Initializes a new instance of the DbProviderFactoryBase class. /// </summary> /// <param name="providerServices">The provider services.</param> protected DbProviderFactoryBase(DbProviderServices providerServices) { this.services = providerServices; }
internal EntityCommandDefinition( DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver = null, BridgeDataReaderFactory bridgeDataReaderFactory = null, ColumnMapFactory columnMapFactory = null) { DebugCheck.NotNull(storeProviderFactory); DebugCheck.NotNull(commandTree); DebugCheck.NotNull(interceptionContext); _bridgeDataReaderFactory = bridgeDataReaderFactory ?? new BridgeDataReaderFactory(); _columnMapFactory = columnMapFactory ?? new ColumnMapFactory(); _storeProviderServices = (resolver != null ? resolver.GetService<DbProviderServices>(storeProviderFactory.GetProviderInvariantName()) : null) ?? storeProviderFactory.GetProviderServices(); try { if (DbCommandTreeKind.Query == commandTree.CommandTreeKind) { // Next compile the plan for the command tree var mappedCommandList = new List<ProviderCommandInfo>(); ColumnMap columnMap; int columnCount; PlanCompiler.Compile(commandTree, out mappedCommandList, out columnMap, out columnCount, out _entitySets); _columnMapGenerators = new IColumnMapGenerator[] { new ConstantColumnMapGenerator(columnMap, columnCount) }; // Note: we presume that the first item in the ProviderCommandInfo is the root node; Debug.Assert(mappedCommandList.Count > 0, "empty providerCommandInfo collection and no exception?"); // this shouldn't ever happen. // Then, generate the store commands from the resulting command tree(s) _mappedCommandDefinitions = new List<DbCommandDefinition>(mappedCommandList.Count); foreach (var providerCommandInfo in mappedCommandList) { var providerCommandDefinition = _storeProviderServices.CreateCommandDefinition( providerCommandInfo.CommandTree, interceptionContext); if (null == providerCommandDefinition) { throw new ProviderIncompatibleException(Strings.ProviderReturnedNullForCreateCommandDefinition); } _mappedCommandDefinitions.Add(providerCommandDefinition); } } else { Debug.Assert( DbCommandTreeKind.Function == commandTree.CommandTreeKind, "only query and function command trees are supported"); var entityCommandTree = (DbFunctionCommandTree)commandTree; // Retrieve mapping and metadata information for the function import. var mapping = GetTargetFunctionMapping(entityCommandTree); IList<FunctionParameter> returnParameters = entityCommandTree.EdmFunction.ReturnParameters; var resultSetCount = returnParameters.Count > 1 ? returnParameters.Count : 1; _columnMapGenerators = new IColumnMapGenerator[resultSetCount]; var storeResultType = DetermineStoreResultType(mapping, 0, out _columnMapGenerators[0]); for (var i = 1; i < resultSetCount; i++) { DetermineStoreResultType(mapping, i, out _columnMapGenerators[i]); } // Copy over parameters (this happens through a more indirect route in the plan compiler, but // it happens nonetheless) var providerParameters = new List<KeyValuePair<string, TypeUsage>>(); foreach (var parameter in entityCommandTree.Parameters) { providerParameters.Add(parameter); } // Construct store command tree usage. var providerCommandTree = new DbFunctionCommandTree( entityCommandTree.MetadataWorkspace, DataSpace.SSpace, mapping.TargetFunction, storeResultType, providerParameters); var storeCommandDefinition = _storeProviderServices.CreateCommandDefinition(providerCommandTree); _mappedCommandDefinitions = new List<DbCommandDefinition>(1) { storeCommandDefinition }; var firstResultEntitySet = mapping.FunctionImport.EntitySets.FirstOrDefault(); if (firstResultEntitySet != null) { _entitySets = new Set<EntitySet>(); _entitySets.Add(mapping.FunctionImport.EntitySets.FirstOrDefault()); _entitySets.MakeReadOnly(); } } // Finally, build a list of the parameters that the resulting command should have; var parameterList = new List<EntityParameter>(); foreach (var queryParameter in commandTree.Parameters) { var parameter = CreateEntityParameterFromQueryParameter(queryParameter); parameterList.Add(parameter); } _parameters = new ReadOnlyCollection<EntityParameter>(parameterList); } catch (EntityCommandCompilationException) { // No need to re-wrap EntityCommandCompilationException throw; } catch (Exception e) { // we should not be wrapping all exceptions if (e.IsCatchableExceptionType()) { // we don't wan't folks to have to know all the various types of exceptions that can // occur, so we just rethrow a CommandDefinitionException and make whatever we caught // the inner exception of it. throw new EntityCommandCompilationException(Strings.EntityClient_CommandDefinitionPreparationFailed, e); } throw; } }
public virtual void SetDefaultProviderServices(DbProviderServices provider, string invariantName) { DebugCheck.NotNull(provider); DebugCheck.NotEmpty(invariantName); _defaultProviderResolvers.Add(new SingletonDependencyResolver<DbProviderServices>(provider, invariantName)); _defaultProviderResolvers.Add(provider); }
/// <summary> /// Initialises a new instance of the <see cref="ProfiledDbProviderServices"/> class. /// </summary> /// <param name="tail">The tail.</param> /// <param name="profiler">The profiler.</param> public ProfiledDbProviderServices(DbProviderServices tail, MiniProfiler profiler) { _wrapped = tail; _profiler = profiler; }
/// <summary> /// Updates storeParameter size, precision and scale properties from user provided parameter properties. /// </summary> private static void SyncParameterProperties( EntityParameter entityParameter, DbParameter storeParameter, DbProviderServices storeProviderServices) { IDbDataParameter dbDataParameter = storeParameter; // DBType is not currently syncable; it's part of the cache key anyway; this is because we can't guarantee // that the store provider will honor it -- (SqlClient doesn't...) //if (entityParameter.IsDbTypeSpecified) //{ // storeParameter.DbType = entityParameter.DbType; //} // Give the store provider the opportunity to set the value before any parameter state has been copied from // the EntityParameter. var parameterTypeUsage = TypeHelpers.GetPrimitiveTypeUsageForScalar(entityParameter.GetTypeUsage()); storeProviderServices.SetParameterValue(storeParameter, parameterTypeUsage, entityParameter.Value); // Override the store provider parameter state with any explicitly specified values from the EntityParameter. if (entityParameter.IsDirectionSpecified) { storeParameter.Direction = entityParameter.Direction; } if (entityParameter.IsIsNullableSpecified) { storeParameter.IsNullable = entityParameter.IsNullable; } if (entityParameter.IsSizeSpecified) { storeParameter.Size = entityParameter.Size; } if (entityParameter.IsPrecisionSpecified) { dbDataParameter.Precision = entityParameter.Precision; } if (entityParameter.IsScaleSpecified) { dbDataParameter.Scale = entityParameter.Scale; } }