コード例 #1
0
        /// <summary>
        /// Saves the Settings
        /// </summary>
        public static void Save()
        {
            XmlWriter xmlWriter = new XmlWriter();

            if (!xmlWriter.Load(SettingsFile))
            {
                if (File.Exists(SettingsFile))
                {
                    try
                    {
                        File.Delete(SettingsFile);
                    }
                    catch (Exception)
                    {
                        return;
                    }
                }

                // create it and reload
                xmlWriter.CreateXmlSettings(SettingsFile);
                xmlWriter.Load(SettingsFile);
            }

            xmlWriter.WriteSetting(cTraktUsername, TraktUsername);
            xmlWriter.WriteSetting(cTraktPassword, TraktPassword);
            xmlWriter.WriteSetting(cTraktOAuthToken, TraktOAuthToken);
            xmlWriter.WriteSetting(cTraktOAuth, TraktOAuth.ToString());
            xmlWriter.WriteSetting(cTVDbAccountId, TVDbAccountIdentifier);
            xmlWriter.WriteSetting(cTMDbSessionId, TMDbSessionId);
            xmlWriter.WriteSetting(cTMDBSyncWatchlist, TMDbSyncWatchlist.ToString());
            xmlWriter.WriteSetting(cIMDbRatingsFilename, IMDbRatingsFilename);
            xmlWriter.WriteSetting(cIMDbWatchlistFilename, IMDbWatchlistFilename);
            xmlWriter.WriteSetting(cIMDbUsername, IMDbUsername);
            xmlWriter.WriteSetting(cIMDBSyncWatchlist, IMDbSyncWatchlist.ToString());
            xmlWriter.WriteSetting(cIMDbCustomLists, IMDbCustomLists.ToJSON());
            xmlWriter.WriteSetting(cListalSyncWatchlist, ListalSyncWatchlist.ToString());
            xmlWriter.WriteSetting(cListalMovieFilename, ListalMovieFilename);
            xmlWriter.WriteSetting(cListalShowFilename, ListalShowFilename);
            xmlWriter.WriteSetting(cCritickerMovieFilename, CritickerMovieFilename);
            xmlWriter.WriteSetting(cLetterboxdRatingsFilename, LetterboxdRatingsFilename);
            xmlWriter.WriteSetting(cLetterboxdWatchedFilename, LetterboxdWatchedFilename);
            xmlWriter.WriteSetting(cLetterboxdDiaryFilename, LetterboxdDiaryFilename);
            xmlWriter.WriteSetting(cFlixsterUserId, FlixsterUserId);
            xmlWriter.WriteSetting(cFlixsterSyncWantToSee, FlixsterSyncWantToSee.ToString());
            xmlWriter.WriteSetting(cMarkAsWatched, MarkAsWatched.ToString());
            xmlWriter.WriteSetting(cIgnoreWatchedForWatchlist, IgnoreWatchedForWatchlist.ToString());
            xmlWriter.WriteSetting(cEnableIMDb, EnableIMDb.ToString());
            xmlWriter.WriteSetting(cEnableTMDb, EnableTMDb.ToString());
            xmlWriter.WriteSetting(cEnableTVDb, EnableTVDb.ToString());
            xmlWriter.WriteSetting(cEnableListal, EnableListal.ToString());
            xmlWriter.WriteSetting(cEnableCriticker, EnableCriticker.ToString());
            xmlWriter.WriteSetting(cEnableLetterboxd, EnableLetterboxd.ToString());
            xmlWriter.WriteSetting(cEnableFlixster, EnableFlixster.ToString());
            xmlWriter.WriteSetting(cLogLevel, ((int)LogSeverityLevel).ToString());
            xmlWriter.WriteSetting(cBatchSize, BatchSize.ToString());
            xmlWriter.WriteSetting(cWatchedOnReleaseDay, WatchedOnReleaseDay.ToString());

            // save file
            xmlWriter.Save(SettingsFile);
        }
コード例 #2
0
        public void DisplayOptions()
        {
            var lines = new List <Tuple <string, string> >
            {
                new Tuple <string, string>("Operations", Operation.ToString()),
                new Tuple <string, string>("Batch size", BatchSize.ToString()),
                new Tuple <string, string>("Client count", ClientCount.ToString()),
                new Tuple <string, string>("Time limit", TimeLimit?.ToString() ?? "<not set>"),
            };

            lines.ForEach(x => Console.WriteLine($"{x.Item1,-12}: {x.Item2}"));
            Console.WriteLine();
        }
コード例 #3
0
        public DbCommand CreateCommand(IQueryable query, IEntityType entity)
        {
            var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName == "EntityFramework.MicrosoftSqlServer, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60");

            if (assembly != null)
            {
                var type = assembly.GetType("Microsoft.Data.Entity.SqlServerMetadataExtensions");
                var sqlServerEntityTypeMethod = type.GetMethod("SqlServer", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(IEntityType) }, null);
                var sqlServerPropertyMethod   = type.GetMethod("SqlServer", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(IProperty) }, null);
                var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity });

                // GET mapping
                var tableName = string.IsNullOrEmpty(sqlServer.Schema) ?
                                string.Concat("[", sqlServer.TableName, "]") :
                                string.Concat("[", sqlServer.Schema, "].[", sqlServer.TableName, "]");

                // GET keys mappings
                var columnKeys = new List <string>();
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                }

                // GET command text template
                var commandTextTemplate = BatchSize > 0 ?
                                          BatchDelayInterval > 0 ?
                                          CommandTextWhileDelayTemplate :
                                          CommandTextWhileTemplate :
                                          CommandTextTemplate;

                // GET inner query
                var relationalCommand = query.CreateCommand();
                var querySelect       = relationalCommand.CommandText;

                // GET primary key join
                var primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.[", x, "] = B.[", x, "]")));

                // REPLACE template
                commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                      .Replace("{Select}", querySelect)
                                      .Replace("{PrimaryKeys}", primaryKeys)
                                      .Replace("{Top}", BatchSize.ToString())
                                      .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"));

                // CREATE command
                var command = query.GetDbContext().CreateStoreCommand();
                command.CommandText = commandTextTemplate;

                // ADD Parameter
                var parameterCollection = relationalCommand.Parameters;
                foreach (var parameter in parameterCollection)
                {
                    var param = command.CreateParameter();
                    param.ParameterName = parameter.Name;
                    param.Value         = parameter.Value;

                    command.Parameters.Add(param);
                }

                return(command);
            }
            return(null);
        }
コード例 #4
0
        /// <summary>Creates a command to execute the batch operation.</summary>
        /// <param name="query">The query.</param>
        /// <param name="entity">The schema entity.</param>
        /// <returns>The new command to execute the batch operation.</returns>
        internal DbCommand CreateCommand <T>(ObjectQuery query, SchemaEntityType <T> entity)
        {
            // GET mapping
            var mapping   = entity.Info.EntityTypeMapping.MappingFragment;
            var store     = mapping.StoreEntitySet;
            var tableName = string.IsNullOrEmpty(store.Schema) ?
                            string.Concat("[", store.Table, "]") :
                            string.Concat("[", store.Schema, "].[", store.Table, "]");

            // GET keys mappings
            var columnKeys = new List <string>();

            foreach (var propertyKey in entity.Info.Key.PropertyRefs)
            {
                var mappingProperty = mapping.ScalarProperties.Find(x => x.Name == propertyKey.Name);

                if (mappingProperty == null)
                {
                    throw new Exception(string.Format(ExceptionMessage.BatchOperations_PropertyNotFound, propertyKey.Name));
                }

                columnKeys.Add(mappingProperty.ColumnName);
            }

            // GET command text template
            var commandTextTemplate = BatchSize > 0 ?
                                      BatchDelayInterval > 0 ?
                                      CommandTextWhileDelayTemplate :
                                      CommandTextWhileTemplate :
                                      CommandTextTemplate;

            // GET inner query
            var querySelect = query.ToTraceString();

            // GET primary key join
            var primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.[", x, "] = B.[", x, "]")));

            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{Top}", BatchSize.ToString())
                                  .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"));

            // CREATE command
            var command = query.Context.CreateStoreCommand();

            command.CommandText = commandTextTemplate;

            // ADD Parameter
            var parameterCollection = query.Parameters;

            foreach (var parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.ParameterName = parameter.Name;
                param.Value         = parameter.Value;

                command.Parameters.Add(param);
            }

            return(command);
        }
コード例 #5
0
        public DbCommand CreateCommand(IQueryable query, IEntityType entity)
        {
#if NETSTANDARD1_3
            try
            {
                Assembly assembly;

                try
                {
                    assembly = Assembly.Load(new AssemblyName("Microsoft.EntityFrameworkCore.SqlServer"));
                }
                catch (Exception ex)
                {
                    throw new Exception(ExceptionMessage.BatchOperations_AssemblyNotFound);
                }

                if (assembly != null)
                {
                    var type = assembly.GetType("Microsoft.EntityFrameworkCore.SqlServerMetadataExtensions");

                    var sqlServerEntityTypeMethod = type.GetMethod("SqlServer", new[] { typeof(IEntityType) });
                    var sqlServerPropertyMethod   = type.GetMethod("SqlServer", new[] { typeof(IProperty) });
                    var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity });

                    // GET mapping
                    var tableName = string.IsNullOrEmpty(sqlServer.Schema) ?
                                    string.Concat("[", sqlServer.TableName, "]") :
                                    string.Concat("[", sqlServer.Schema, "].[", sqlServer.TableName, "]");

                    // GET keys mappings
                    var columnKeys = new List <string>();
                    foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                    {
                        var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey });

                        var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                        columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                    }

                    // GET command text template
                    var commandTextTemplate = BatchSize > 0 ?
                                              BatchDelayInterval > 0 ?
                                              CommandTextWhileDelayTemplate :
                                              CommandTextWhileTemplate :
                                              CommandTextTemplate;

                    // GET inner query
#if EFCORE
                    RelationalQueryContext queryContext;
                    var relationalCommand = query.CreateCommand(out queryContext);
#else
                    var relationalCommand = query.CreateCommand();
#endif

                    var querySelect = relationalCommand.CommandText;

                    // GET primary key join
                    var primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.[", x, "] = B.[", x, "]")));

                    // REPLACE template
                    commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                          .Replace("{Select}", querySelect)
                                          .Replace("{PrimaryKeys}", primaryKeys)
                                          .Replace("{Top}", BatchSize.ToString())
                                          .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"));

                    // CREATE command
                    var command = query.GetDbContext().CreateStoreCommand();
                    command.CommandText = commandTextTemplate;

#if EFCORE
                    // ADD Parameter
                    foreach (var relationalParameter in relationalCommand.Parameters)
                    {
                        var parameter = queryContext.ParameterValues[relationalParameter.InvariantName];

                        var param = command.CreateParameter();
                        param.ParameterName = relationalParameter.InvariantName;
                        param.Value         = parameter ?? DBNull.Value;

                        command.Parameters.Add(param);
                    }
#else
                    // ADD Parameter
                    var parameterCollection = relationalCommand.Parameters;
                    foreach (var parameter in parameterCollection)
                    {
                        var param = command.CreateParameter();
                        param.ParameterName = parameter.Name;
                        param.Value         = parameter.Value ?? DBNull.Value;

                        command.Parameters.Add(param);
                    }
#endif

                    return(command);
                }
                return(null);
            }
            catch (Exception)
            {
                return(null);
            }
#else
            var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith("Microsoft.EntityFrameworkCore.SqlServer", StringComparison.InvariantCulture));

            if (assembly != null)
            {
                var type = assembly.GetType("Microsoft.EntityFrameworkCore.SqlServerMetadataExtensions");
                var sqlServerEntityTypeMethod = type.GetMethod("SqlServer", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(IEntityType) }, null);
                var sqlServerPropertyMethod   = type.GetMethod("SqlServer", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(IProperty) }, null);
                var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity });

                // GET mapping
                var tableName = string.IsNullOrEmpty(sqlServer.Schema) ?
                                string.Concat("[", sqlServer.TableName, "]") :
                                string.Concat("[", sqlServer.Schema, "].[", sqlServer.TableName, "]");

                // GET keys mappings
                var columnKeys = new List <string>();
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                }

                // GET command text template
                var commandTextTemplate = BatchSize > 0 ?
                                          BatchDelayInterval > 0 ?
                                          CommandTextWhileDelayTemplate :
                                          CommandTextWhileTemplate :
                                          CommandTextTemplate;

                // GET inner query
#if EFCORE
                RelationalQueryContext queryContext;
                var relationalCommand = query.CreateCommand(out queryContext);
#else
                var relationalCommand = query.CreateCommand();
#endif
                var querySelect = relationalCommand.CommandText;

                // GET primary key join
                var primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.[", x, "] = B.[", x, "]")));

                // REPLACE template
                commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                      .Replace("{Select}", querySelect)
                                      .Replace("{PrimaryKeys}", primaryKeys)
                                      .Replace("{Top}", BatchSize.ToString())
                                      .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"));

                // CREATE command
                var command = query.GetDbContext().CreateStoreCommand();
                command.CommandText = commandTextTemplate;

#if EFCORE
                // ADD Parameter
                foreach (var relationalParameter in relationalCommand.Parameters)
                {
                    var parameter = queryContext.ParameterValues[relationalParameter.InvariantName];

                    var param = command.CreateParameter();
                    param.ParameterName = relationalParameter.InvariantName;
                    param.Value         = parameter ?? DBNull.Value;

                    command.Parameters.Add(param);
                }
#else
                // ADD Parameter
                var parameterCollection = relationalCommand.Parameters;
                foreach (var parameter in parameterCollection)
                {
                    var param = command.CreateParameter();
                    param.ParameterName = parameter.Name;
                    param.Value         = parameter.Value ?? DBNull.Value;

                    command.Parameters.Add(param);
                }
#endif

                return(command);
            }
            return(null);
#endif
        }
コード例 #6
0
        /// <summary>Creates a command to execute the batch operation.</summary>
        /// <exception cref="Exception">Thrown when an exception error condition occurs.</exception>
        /// <typeparam name="T">Generic type parameter.</typeparam>
        /// <param name="query">The query.</param>
        /// <param name="entity">The schema entity.</param>
        /// <param name="visitor">The visitor.</param>
        /// <returns>The new command to execute the batch operation.</returns>
        internal DbCommand CreateCommand <T>(ObjectQuery query, SchemaEntityType <T> entity)
        {
            // GET command
            var command = query.Context.CreateStoreCommand();

            bool isMySql  = command.GetType().FullName.Contains("MySql");
            var  isSqlCe  = command.GetType().Name == "SqlCeCommand";
            var  isOracle = command.GetType().Namespace.Contains("Oracle");

            // Oracle BindByName
            if (isOracle)
            {
                var bindByNameProperty = command.GetType().GetProperty("BindByName") ?? command.GetType().GetProperty("PassParametersByName");
                if (bindByNameProperty != null)
                {
                    bindByNameProperty.SetValue(command, true, null);
                }
            }

            // GET mapping
            var mapping = entity.Info.EntityTypeMapping.MappingFragment;
            var store   = mapping.StoreEntitySet;

            string tableName;

            if (isMySql)
            {
                tableName = string.Concat("`", store.Table, "`");
            }
            else if (isSqlCe)
            {
                tableName = string.Concat("[", store.Table, "]");
            }
            else if (isOracle)
            {
                tableName = string.IsNullOrEmpty(store.Schema) || store.Schema == "dbo" ?
                            string.Concat("\"", store.Table, "\"") :
                            string.Concat("\"", store.Schema, "\".\"", store.Table, "\"");
            }
            else
            {
                tableName = string.IsNullOrEmpty(store.Schema) ?
                            string.Concat("[", store.Table, "]") :
                            string.Concat("[", store.Schema, "].[", store.Table, "]");
            }

            // GET keys mappings
            var columnKeys = new List <string>();

            foreach (var propertyKey in entity.Info.Key.PropertyRefs)
            {
                var mappingProperty = mapping.ScalarProperties.Find(x => x.Name == propertyKey.Name);

                if (mappingProperty == null)
                {
                    throw new Exception(string.Format(ExceptionMessage.BatchOperations_PropertyNotFound, propertyKey.Name));
                }

                columnKeys.Add(mappingProperty.ColumnName);
            }

            // GET command text template
            var commandTextTemplate = command.GetType().Name == "NpgsqlCommand" ?
                                      CommandTextPostgreSQLTemplate :
                                      isOracle ?
                                      CommandTextOracleTemplate :
                                      isMySql ?
                                      CommandTextTemplate_MySql :
                                      isSqlCe ?
                                      CommandTextSqlCeTemplate :
                                      BatchSize > 0 ?
                                      BatchDelayInterval > 0 ?
                                      CommandTextWhileDelayTemplate :
                                      CommandTextWhileTemplate :
                                      CommandTextTemplate;

            // GET inner query
            var customQuery = query.GetCommandTextAndParameters();
            var querySelect = customQuery.Item1;

            // GET primary key join
            string primaryKeys;

            if (isSqlCe || isOracle)
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + ".", EscapeName(x, isMySql, isOracle), " = B.", EscapeName(x, isMySql, isOracle), "")));
            }
            else
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.", EscapeName(x, isMySql, isOracle), " = B.", EscapeName(x, isMySql, isOracle), "")));
            }

            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{Top}", BatchSize.ToString())
                                  .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"));

            // CREATE command
            command.CommandText = commandTextTemplate;

            // ADD Parameter
            var parameterCollection = customQuery.Item2;

#if EF5
            foreach (ObjectParameter parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.ParameterName = parameter.Name;
                param.Value         = parameter.Value ?? DBNull.Value;

                command.Parameters.Add(param);
            }
#elif EF6
            foreach (DbParameter parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.ParameterName = parameter.ParameterName;
                param.Value         = parameter.Value ?? DBNull.Value;

                command.Parameters.Add(param);
            }
#endif

            return(command);
        }
コード例 #7
0
        public DbCommand CreateCommand(IQueryable query, IEntityType entity)
        {
            var context = query.GetDbContext();

            var databaseCreator = context.Database.GetService <IDatabaseCreator>();

            var assembly     = databaseCreator.GetType().GetTypeInfo().Assembly;
            var assemblyName = assembly.GetName().Name;

            MethodInfo dynamicProviderEntityType = null;
            MethodInfo dynamicProviderProperty   = null;

            bool isSqlServer   = false;
            bool isPostgreSQL  = false;
            bool isMySql       = false;
            bool isMySqlPomelo = false;
            bool isSQLite      = false;

            if (assemblyName == "Microsoft.EntityFrameworkCore.SqlServer")
            {
                isSqlServer = true;
                var type = assembly.GetType("Microsoft.EntityFrameworkCore.SqlServerMetadataExtensions");
                dynamicProviderEntityType = type.GetMethod("SqlServer", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = type.GetMethod("SqlServer", new[] { typeof(IProperty) });
            }
            else if (assemblyName == "Npgsql.EntityFrameworkCore.PostgreSQL")
            {
                isPostgreSQL = true;
                var type = assembly.GetType("Microsoft.EntityFrameworkCore.NpgsqlMetadataExtensions");
                dynamicProviderEntityType = type.GetMethod("Npgsql", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = type.GetMethod("Npgsql", new[] { typeof(IProperty) });
            }
            else if (assemblyName == "MySql.Data.EntityFrameworkCore")
            {
                isMySql = true;
                var type = assembly.GetType("MySQL.Data.EntityFrameworkCore.MySQLMetadataExtensions");
                dynamicProviderEntityType = type.GetMethod("MySQL", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = type.GetMethod("MySQL", new[] { typeof(IProperty) });
            }
            else if (assemblyName == "Pomelo.EntityFrameworkCore.MySql")
            {
                isMySqlPomelo = true;
                var type = assembly.GetType("Microsoft.EntityFrameworkCore.MySqlMetadataExtensions");
                dynamicProviderEntityType = type.GetMethod("MySql", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = type.GetMethod("MySql", new[] { typeof(IProperty) });
            }
            else if (assemblyName == "Microsoft.EntityFrameworkCore.Sqlite")
            {
                isSQLite = true;

                // CHANGE all for this one?
                dynamicProviderEntityType = typeof(RelationalMetadataExtensions).GetMethod("Relational", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = typeof(RelationalMetadataExtensions).GetMethod("Relational", new[] { typeof(IProperty) });
            }
            else
            {
                throw new Exception(string.Format(ExceptionMessage.Unsupported_Provider, assemblyName));
            }


            string tableName   = "";
            var    columnKeys  = new List <string>();
            string primaryKeys = "";

            if (isSqlServer)
            {
                var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                // GET mapping
                tableName = string.IsNullOrEmpty(sqlServer.Schema) ?
                            string.Concat("[", sqlServer.TableName, "]") :
                            string.Concat("[", sqlServer.Schema, "].[", sqlServer.TableName, "]");

                // GET keys mappings
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                }

                // GET primary key join
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.[", x, "] = B.[", x, "]")));
            }
            else if (isPostgreSQL)
            {
                var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                // GET mapping
                tableName = string.IsNullOrEmpty(sqlServer.Schema) ?
                            string.Concat("\"", sqlServer.TableName, "\"") :
                            string.Concat("\"", sqlServer.Schema, "\".\"", sqlServer.TableName, "\"");

                // GET keys mappings
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                }

                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.\"", x, "\" = B.\"", x, "\"")));
            }
            else if (isMySqlPomelo)
            {
                var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                // GET mapping
                tableName = string.Concat("`", sqlServer.TableName, "`");

                // GET keys mappings
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                }

                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.`", x, "` = B.`", x, "`")));
            }
            else if (isMySql)
            {
                var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                // GET mapping
                tableName = string.Concat("`", sqlServer.TableName, "`");

                // GET keys mappings
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                }

                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.`", x, "` = B.`", x, "`")));
            }
            else if (isSQLite)
            {
                var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                // GET mapping
                tableName = string.Concat("\"", sqlServer.TableName, "\"");

                // GET keys mappings
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                }

                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + "." + "\"" + x + "\"", " = B.\"", x, "\"")));
            }


            // GET command text template
            var commandTextTemplate = isPostgreSQL ?
                                      CommandTextPostgreSQLTemplate :
                                      isMySql || isMySqlPomelo ?
                                      CommandTextTemplate_MySql :
                                      isSQLite ?
                                      CommandTextSQLiteTemplate :
                                      BatchSize > 0 ?
                                      BatchDelayInterval > 0 ?
                                      CommandTextWhileDelayTemplate :
                                      CommandTextWhileTemplate :
                                      CommandTextTemplate;

            // GET inner query
#if EFCORE
            RelationalQueryContext queryContext;
            var relationalCommand = query.CreateCommand(out queryContext);
#else
            var relationalCommand = query.CreateCommand();
#endif
            var querySelect = relationalCommand.CommandText;


            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{Top}", BatchSize.ToString())
                                  .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"))
                                  .Replace("{Hint}", UseTableLock ? "WITH ( TABLOCK )" : "");

            // CREATE command
            var command = query.GetDbContext().CreateStoreCommand();
            command.CommandText = commandTextTemplate;

#if EFCORE
            // ADD Parameter
            foreach (var relationalParameter in relationalCommand.Parameters)
            {
                var parameter = queryContext.ParameterValues[relationalParameter.InvariantName];

                var param = command.CreateParameter();
                param.CopyFrom(relationalParameter, parameter);

                command.Parameters.Add(param);
            }
#else
            // ADD Parameter
            var parameterCollection = relationalCommand.Parameters;
            foreach (var parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.CopyFrom(parameter);

                command.Parameters.Add(param);
            }
#endif

            return(command);
        }
コード例 #8
0
        /// <summary>Creates a command to execute the batch operation.</summary>
        /// <exception cref="Exception">Thrown when an exception error condition occurs.</exception>
        /// <typeparam name="T">Generic type parameter.</typeparam>
        /// <param name="query">The query.</param>
        /// <param name="tdTableDefinition">The schema entity.</param>
        /// <returns>The new command to execute the batch operation.</returns>
        public DbCommand CreateCommand(ObjectQuery query, TableDefinition tdTableDefinition)
        {
            // GET command
            var command = query.Context.CreateStoreCommand();

            bool isPostgreSql = command.GetType().Name == "NpgsqlCommand";
            bool isMySql      = command.GetType().FullName.Contains("MySql");
            var  isSqlCe      = command.GetType().Name == "SqlCeCommand";
            var  isOracle     = command.GetType().Namespace.Contains("Oracle");
            var  isSQLite     = command.GetType().Namespace.Contains("SQLite");

            // Oracle BindByName
            if (isOracle)
            {
                var bindByNameProperty = command.GetType().GetProperty("BindByName") ?? command.GetType().GetProperty("PassParametersByName");
                if (bindByNameProperty != null)
                {
                    bindByNameProperty.SetValue(command, true, null);
                }
            }

            string tableName;

            if (isMySql)
            {
                tableName = string.Concat("`", tdTableDefinition.Table, "`");
            }
            else if (isSqlCe)
            {
                tableName = string.Concat("[", tdTableDefinition.Table, "]");
            }
            else if (isSQLite)
            {
                tableName = string.Concat("\"", tdTableDefinition.Table, "\"");
            }
            else if (isOracle)
            {
                tableName = string.IsNullOrEmpty(tdTableDefinition.Schema) || tdTableDefinition.Schema == "dbo" ?
                            string.Concat("\"", tdTableDefinition.Table, "\"") :
                            string.Concat("\"", tdTableDefinition.Schema, "\".\"", tdTableDefinition.Table, "\"");
            }
            else
            {
                tableName = string.IsNullOrEmpty(tdTableDefinition.Schema) ?
                            string.Concat("[", tdTableDefinition.Table, "]") :
                            string.Concat("[", tdTableDefinition.Schema, "].[", tdTableDefinition.Table, "]");
            }

            // GET command text template
            var commandTextTemplate = isPostgreSql ?
                                      CommandTextPostgreSQLTemplate :
                                      isOracle ?
                                      CommandTextOracleTemplate :
                                      isMySql ?
                                      CommandTextTemplate_MySql :
                                      isSqlCe ?
                                      CommandTextSqlCeTemplate :
                                      isSQLite ?
                                      CommandTextSQLiteTemplate :
                                      BatchSize > 0 ?
                                      BatchDelayInterval > 0 ?
                                      CommandTextWhileDelayTemplate :
                                      CommandTextWhileTemplate :
                                      CommandTextTemplate;

            // GET inner query
            var customQuery = query.GetCommandTextAndParameters();

            if (customQuery.Item1.EndsWith("WHERE 1 = 0", StringComparison.InvariantCultureIgnoreCase))
            {
                return(null);
            }

            if (isPostgreSql && customQuery.Item1.EndsWith("WHERE TRUE = FALSE", StringComparison.InvariantCultureIgnoreCase))
            {
                return(null);
            }

            var querySelect = customQuery.Item1;

            // GET primary key join
            string primaryKeys;

            if (isSqlCe || isOracle || isSQLite)
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", tdTableDefinition.Keys.Select(x => string.Concat(tableName + ".", EscapeName(x.ColumnName, isMySql, isOracle), " = B.", EscapeName(x.ColumnName, isMySql, isOracle), "")));
            }
            else
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", tdTableDefinition.Keys.Select(x => string.Concat("A.", EscapeName(x.ColumnName, isMySql, isOracle), " = B.", EscapeName(x.ColumnName, isMySql, isOracle), "")));
            }

            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{Top}", BatchSize.ToString())
                                  .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"))
                                  .Replace("{Hint}", UseTableLock ? "WITH ( TABLOCK )" : "");

            // CREATE command
            command.CommandText = commandTextTemplate;

            // ADD Parameter
            var parameterCollection = customQuery.Item2;

#if EF5
            foreach (ObjectParameter parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.CopyFrom(parameter);

                command.Parameters.Add(param);
            }
#elif EF6
            foreach (DbParameter parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.CopyFrom(parameter);

                command.Parameters.Add(param);
            }
#endif

            return(command);
        }
コード例 #9
0
        public DbCommand CreateCommand(IQueryable query, IEntityType entity)
        {
            var context = query.GetDbContext();

            var databaseCreator = context.Database.GetService <IDatabaseCreator>();

            var assembly     = databaseCreator.GetType().GetTypeInfo().Assembly;
            var assemblyName = assembly.GetName().Name;

            MethodInfo dynamicProviderEntityType = null;
            MethodInfo dynamicProviderProperty   = null;

            bool isSqlServer   = false;
            bool isPostgreSQL  = false;
            bool isMySql       = false;
            bool isMySqlPomelo = false;
            bool isSQLite      = false;
            bool isOracle      = false;
            bool isDevOracle   = false;

            if (assemblyName == "Microsoft.EntityFrameworkCore.SqlServer")
            {
                isSqlServer = true;
                var type = assembly.GetType("Microsoft.EntityFrameworkCore.SqlServerMetadataExtensions");
                dynamicProviderEntityType = type.GetMethod("SqlServer", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = type.GetMethod("SqlServer", new[] { typeof(IProperty) });
            }
            else if (assemblyName == "Npgsql.EntityFrameworkCore.PostgreSQL")
            {
                isPostgreSQL = true;
                var type = assembly.GetType("Microsoft.EntityFrameworkCore.NpgsqlMetadataExtensions");
                dynamicProviderEntityType = type.GetMethod("Npgsql", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = type.GetMethod("Npgsql", new[] { typeof(IProperty) });
            }
            else if (assemblyName == "MySql.Data.EntityFrameworkCore")
            {
                isMySql = true;
                var type = assembly.GetType("MySQL.Data.EntityFrameworkCore.MySQLMetadataExtensions");
                dynamicProviderEntityType = type.GetMethod("MySQL", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = type.GetMethod("MySQL", new[] { typeof(IProperty) });
            }
            else if (assemblyName == "Pomelo.EntityFrameworkCore.MySql")
            {
                isMySqlPomelo = true;
                var type = assembly.GetType("Microsoft.EntityFrameworkCore.MySqlMetadataExtensions");
                dynamicProviderEntityType = type.GetMethod("MySql", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = type.GetMethod("MySql", new[] { typeof(IProperty) });
            }
            else if (assemblyName == "Microsoft.EntityFrameworkCore.Sqlite")
            {
                isSQLite = true;

                // CHANGE all for this one?
                dynamicProviderEntityType = typeof(RelationalMetadataExtensions).GetMethod("Relational", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = typeof(RelationalMetadataExtensions).GetMethod("Relational", new[] { typeof(IProperty) });
            }
            else if (assemblyName == "Oracle.EntityFrameworkCore")
            {
                isOracle = true;

                // CHANGE all for this one?
                dynamicProviderEntityType = typeof(RelationalMetadataExtensions).GetMethod("Relational", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = typeof(RelationalMetadataExtensions).GetMethod("Relational", new[] { typeof(IProperty) });
            }
            else if (assemblyName == "Devart.Data.Oracle.Entity.EFCore")
            {
                isDevOracle = true;

                // CHANGE all for this one?
                dynamicProviderEntityType = typeof(RelationalMetadataExtensions).GetMethod("Relational", new[] { typeof(IEntityType) });
                dynamicProviderProperty   = typeof(RelationalMetadataExtensions).GetMethod("Relational", new[] { typeof(IProperty) });
            }
            else
            {
                throw new Exception(string.Format(ExceptionMessage.Unsupported_Provider, assemblyName));
            }


            string tableName   = "";
            var    columnKeys  = new List <string>();
            string primaryKeys = "";

            if (isSqlServer)
            {
                List <Tuple <string, string> > propertyAndColumnName = new List <Tuple <string, string> >();
                var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                // GET mapping
                tableName = string.IsNullOrEmpty(sqlServer.Schema) ?
                            string.Concat("[", sqlServer.TableName, "]") :
                            string.Concat("[", sqlServer.Schema, "].[", sqlServer.TableName, "]");

                // GET keys mappings
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    //columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                    propertyAndColumnName.Add(new Tuple <string, string>(propertyKey.Name, (string)columnNameProperty.GetValue(mappingProperty)));
                }

                // GET primary key join
                primaryKeys = propertyAndColumnName.Count > 1?
                              string.Join(Environment.NewLine + "AND ", propertyAndColumnName.Select(x => string.Concat("A.[", x.Item2, "] = B.[", x.Item1, "]"))):
                              string.Join(Environment.NewLine + "AND ", propertyAndColumnName.Select(x => string.Concat("A.[", x.Item2, "] = B.[", x.Item2, "]")));
            }
            else if (isPostgreSQL)
            {
                List <Tuple <string, string> > propertyAndColumnName = new List <Tuple <string, string> >();
                var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                // GET mapping
                tableName = string.IsNullOrEmpty(sqlServer.Schema) ?
                            string.Concat("\"", sqlServer.TableName, "\"") :
                            string.Concat("\"", sqlServer.Schema, "\".\"", sqlServer.TableName, "\"");

                // GET keys mappings
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    //columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                    propertyAndColumnName.Add(new Tuple <string, string>(propertyKey.Name, (string)columnNameProperty.GetValue(mappingProperty)));
                }

                primaryKeys = string.Join(Environment.NewLine + "AND ", propertyAndColumnName.Select(x => string.Concat("A.\"", x.Item2, "\" = B.\"", x.Item1, "\"")));
            }
            else if (isMySqlPomelo)
            {
                if (dynamicProviderEntityType == null)
                {
                    // GET mapping
                    tableName = string.Concat("`", entity.Relational().TableName, "`");

                    // GET keys mappings
                    foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                    {
                        columnKeys.Add(propertyKey.Relational().ColumnName);
                    }

                    primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.`", x, "` = B.`", x, "`")));
                }
                else
                {
                    var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                    // GET mapping
                    tableName = string.Concat("`", sqlServer.TableName, "`");

                    // GET keys mappings
                    foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                    {
                        var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                        var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                        columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                    }

                    primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.`", x, "` = B.`", x, "`")));
                }
            }
            else if (isMySql)
            {
                var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                // GET mapping
                tableName = string.Concat("`", sqlServer.TableName, "`");

                // GET keys mappings
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                }

                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.`", x, "` = B.`", x, "`")));
            }
            else if (isSQLite)
            {
                var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                // GET mapping
                tableName = string.Concat("\"", sqlServer.TableName, "\"");

                // GET keys mappings
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                }

                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + "." + "\"" + x + "\"", " = B.\"", x, "\"")));
            }
            else if (isOracle || isDevOracle)
            {
                var sqlServer = (IRelationalEntityTypeAnnotations)dynamicProviderEntityType.Invoke(null, new[] { entity });

                // GET mapping
                tableName = string.IsNullOrEmpty(sqlServer.Schema) ? string.Concat("\"", sqlServer.TableName, "\"") : string.Concat("\"", sqlServer.Schema, "\".\"", sqlServer.TableName, "\"");

                // GET keys mappings
                foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                {
                    var mappingProperty = dynamicProviderProperty.Invoke(null, new[] { propertyKey });

                    var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                    columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                }

                // GET primary key join
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + ".\"", x, "\" = B.\"", x, "\"")));
            }

            // GET command text template
            var commandTextTemplate = isPostgreSQL ?
                                      CommandTextPostgreSQLTemplate :
                                      isMySql || isMySqlPomelo ?
                                      CommandTextTemplate_MySql :
                                      isSQLite ?
                                      CommandTextSQLiteTemplate :
                                      (isOracle || isDevOracle) ?
                                      CommandTextOracleTemplate :
                                      BatchSize > 0 ?
                                      BatchDelayInterval > 0 ?
                                      CommandTextWhileDelayTemplate :
                                      CommandTextWhileTemplate :
                                      CommandTextTemplate;

            // GET inner query
#if EFCORE
            RelationalQueryContext queryContext;
            var relationalCommand = query.CreateCommand(out queryContext);
#else
            var relationalCommand = query.CreateCommand();
#endif
            var querySelect = relationalCommand.CommandText;


            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{Top}", BatchSize.ToString())
                                  .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"))
                                  .Replace("{Hint}", UseTableLock ? "WITH ( TABLOCK )" : "");

            // CREATE command
            var command = query.GetDbContext().CreateStoreCommand();
            command.CommandText = commandTextTemplate;

#if EFCORE
            // ADD Parameter
            foreach (var relationalParameter in relationalCommand.Parameters)
            {
                object parameter;
                string name = "";

#if NETSTANDARD2_0
                if (isOracle || isDevOracle)
                {
                    name = ((dynamic)relationalParameter).Name;
                }
                else
                {
#endif
                name = relationalParameter.InvariantName;
#if NETSTANDARD2_0
            }
#endif

                if (!queryContext.ParameterValues.TryGetValue(relationalParameter.InvariantName, out parameter))
                {
                    if (relationalParameter.InvariantName.StartsWith("__ef_filter"))
                    {
                        throw new Exception("Please use 'IgnoreQueryFilters()'. The HasQueryFilter is not yet supported.");
                    }
                    else
                    {
                        throw new Exception("The following parameter could not be found: " + relationalParameter);
                    }
                }

                var param = command.CreateParameter();
                param.CopyFrom(relationalParameter, parameter, name);

#if !NETSTANDARD1_3
                if (isPostgreSQL)
                {
                    Type itemType = param.Value.GetType();

                    if (itemType.IsEnum)
                    {
                        var underlyingType = Enum.GetUnderlyingType(itemType);
                        param.Value = Convert.ChangeType(param.Value, underlyingType);
                    }
                }
#endif

                command.Parameters.Add(param);
            }
#else
            // ADD Parameter
            var parameterCollection = relationalCommand.Parameters;
            foreach (var parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.CopyFrom(parameter);

                command.Parameters.Add(param);
            }
#endif

            return(command);
        }
コード例 #10
0
        public DbCommand CreateCommand(IQueryable query, IEntityType entity)
        {
#if NETSTANDARD1_3
            Assembly assembly           = null;
            Assembly postgreSqlAssembly = null;
            Assembly mySqlPomelo        = null;
            Assembly mySql = null;

            try
            {
                assembly = Assembly.Load(new AssemblyName("Microsoft.EntityFrameworkCore.SqlServer"));
            }
            catch (Exception ex)
            {
                try
                {
                    postgreSqlAssembly = Assembly.Load(new AssemblyName("Npgsql.EntityFrameworkCore.PostgreSQL"));
                }
                catch
                {
                    try
                    {
                        mySql = Assembly.Load(new AssemblyName("MySql.Data.EntityFrameworkCore"));
                    }
                    catch
                    {
                        try
                        {
                            mySqlPomelo = Assembly.Load(new AssemblyName("Pomelo.EntityFrameworkCore.MySql"));
                        }
                        catch
                        {
                            throw new Exception(ExceptionMessage.BatchOperations_AssemblyNotFound);
                        }
                    }
                }
            }
#else
            var assembly           = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith("Microsoft.EntityFrameworkCore.SqlServer", StringComparison.InvariantCulture));
            var postgreSqlAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith("Npgsql.EntityFrameworkCore.PostgreSQL", StringComparison.InvariantCulture));
            var mySqlPomelo        = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith("Pomelo.EntityFrameworkCore.MySql", StringComparison.InvariantCulture));
            var mySql = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith("MySql.Data.EntityFrameworkCore", StringComparison.InvariantCulture));
#endif
            if (assembly != null || postgreSqlAssembly != null || mySqlPomelo != null || mySql != null)
            {
                string tableName   = "";
                var    columnKeys  = new List <string>();
                string primaryKeys = "";

                if (assembly != null)
                {
                    var type = assembly.GetType("Microsoft.EntityFrameworkCore.SqlServerMetadataExtensions");
                    var sqlServerEntityTypeMethod = type.GetMethod("SqlServer", new[] { typeof(IEntityType) });
                    var sqlServerPropertyMethod   = type.GetMethod("SqlServer", new[] { typeof(IProperty) });
                    var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity });

                    // GET mapping
                    tableName = string.IsNullOrEmpty(sqlServer.Schema) ?
                                string.Concat("[", sqlServer.TableName, "]") :
                                string.Concat("[", sqlServer.Schema, "].[", sqlServer.TableName, "]");

                    // GET keys mappings
                    foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                    {
                        var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey });

                        var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                        columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                    }

                    // GET primary key join
                    primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.[", x, "] = B.[", x, "]")));
                }
                else if (postgreSqlAssembly != null)
                {
                    var type = postgreSqlAssembly.GetType("Microsoft.EntityFrameworkCore.NpgsqlMetadataExtensions");
                    var sqlServerEntityTypeMethod = type.GetMethod("Npgsql", new[] { typeof(IEntityType) });
                    var sqlServerPropertyMethod   = type.GetMethod("Npgsql", new[] { typeof(IProperty) });
                    var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity });

                    // GET mapping
                    tableName = string.IsNullOrEmpty(sqlServer.Schema) ?
                                string.Concat("\"", sqlServer.TableName, "\"") :
                                string.Concat("\"", sqlServer.Schema, "\".\"", sqlServer.TableName, "\"");

                    // GET keys mappings
                    foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                    {
                        var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey });

                        var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                        columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                    }

                    primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.\"", x, "\" = B.\"", x, "\"")));
                }
                else if (mySqlPomelo != null)
                {
                    var type = mySqlPomelo.GetType("Microsoft.EntityFrameworkCore.MySqlMetadataExtensions");
                    var sqlServerEntityTypeMethod = type.GetMethod("MySql", new[] { typeof(IEntityType) });
                    var sqlServerPropertyMethod   = type.GetMethod("MySql", new[] { typeof(IProperty) });
                    var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity });

                    // GET mapping
                    tableName = string.Concat("`", sqlServer.TableName, "`");

                    // GET keys mappings
                    foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                    {
                        var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey });

                        var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                        columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                    }

                    primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.`", x, "` = B.`", x, "`")));
                }
                else if (mySql != null)
                {
                    var type = mySql.GetType("MySQL.Data.EntityFrameworkCore.MySQLMetadataExtensions");
                    var sqlServerEntityTypeMethod = type.GetMethod("MySQL", new[] { typeof(IEntityType) });
                    var sqlServerPropertyMethod   = type.GetMethod("MySQL", new[] { typeof(IProperty) });
                    var sqlServer = (IRelationalEntityTypeAnnotations)sqlServerEntityTypeMethod.Invoke(null, new[] { entity });

                    // GET mapping
                    tableName = string.Concat("`", sqlServer.TableName, "`");

                    // GET keys mappings
                    foreach (var propertyKey in entity.GetKeys().ToList()[0].Properties)
                    {
                        var mappingProperty = sqlServerPropertyMethod.Invoke(null, new[] { propertyKey });

                        var columnNameProperty = mappingProperty.GetType().GetProperty("ColumnName", BindingFlags.Public | BindingFlags.Instance);
                        columnKeys.Add((string)columnNameProperty.GetValue(mappingProperty));
                    }

                    primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.`", x, "` = B.`", x, "`")));
                }


                // GET command text template
                var commandTextTemplate = assembly == null && postgreSqlAssembly != null ?
                                          CommandTextPostgreSQLTemplate :
                                          mySqlPomelo != null || mySql != null ?
                                          CommandTextTemplate_MySql :
                                          BatchSize > 0 ?
                                          BatchDelayInterval > 0 ?
                                          CommandTextWhileDelayTemplate :
                                          CommandTextWhileTemplate :
                                          CommandTextTemplate;

                // GET inner query
#if EFCORE
                RelationalQueryContext queryContext;
                var relationalCommand = query.CreateCommand(out queryContext);
#else
                var relationalCommand = query.CreateCommand();
#endif
                var querySelect = relationalCommand.CommandText;


                // REPLACE template
                commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                      .Replace("{Select}", querySelect)
                                      .Replace("{PrimaryKeys}", primaryKeys)
                                      .Replace("{Top}", BatchSize.ToString())
                                      .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"))
                                      .Replace("{Hint}", UseTableLock ? "WITH ( TABLOCK )" : "");

                // CREATE command
                var command = query.GetDbContext().CreateStoreCommand();
                command.CommandText = commandTextTemplate;

#if EFCORE
                // ADD Parameter
                foreach (var relationalParameter in relationalCommand.Parameters)
                {
                    var parameter = queryContext.ParameterValues[relationalParameter.InvariantName];

                    var param = command.CreateParameter();
                    param.CopyFrom(relationalParameter, parameter);

                    command.Parameters.Add(param);
                }
#else
                // ADD Parameter
                var parameterCollection = relationalCommand.Parameters;
                foreach (var parameter in parameterCollection)
                {
                    var param = command.CreateParameter();
                    param.CopyFrom(parameter);

                    command.Parameters.Add(param);
                }
#endif

                return(command);
            }
            return(null);
        }