Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Collections.ObjectModel;
- using System.Collections.Generic;
- using System.Reflection;
- public interface IDbConnection { }
- public interface IDbTransaction { }
- public class CommandDefinition { }
- public class DapperRow { }
- public enum CommandType { }
- public static class SqlMapper
- {
- public static IEnumerable<dynamic> Query(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null) => null;
- public static IEnumerable<T> Query<T>(this IDbConnection cnn, CommandDefinition command) => null;
- public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
- where T : new()
- {
- return (new T[] { new T() });
- }
- public static IEnumerable<TReturn> Query<TFirst, TSecond, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => null;
- public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => null;
- public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => null;
- public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => null;
- public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => null;
- public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => null;
- public static IEnumerable<TReturn> Query<TReturn>(this IDbConnection cnn, string sql, Type[] types, Func<object[], TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => null;
- }
- class Solution
- {
- public class baseTable { }
- public class LOGS : baseTable { }
- public class TRACK_EVENT : baseTable { }
- public static class MNLZContext
- {
- public class DbConnection : IDbConnection { }
- public static IDbConnection oracleConnect = new DbConnection();
- }
- public Dictionary<string, object> dbTables = new Dictionary<string, object>();
- public object getTableRows(string tableName, string sqlWhere = @"")
- {
- // взять тип таблицы, сидящей в dbTables[tableName]
- Type tableType = dbTables[tableName].GetType();
- // проверить полученный тип
- if (tableType.GetGenericTypeDefinition() != typeof(ObservableCollection<>))
- throw new ArgumentException("Непонятный класс элемента dbTables[tableName]");
- // взять единственный generic-аргумент сконструированного класса ObservableCollection<T>
- Type itemType = tableType.GetGenericArguments()[0];
- // получить обобщённый метод SqlMapper.Query<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
- MethodInfo generic_method = typeof(SqlMapper).GetMethods()
- .Where(m => m.Name.Equals("Query"))
- .Where(m => m.IsStatic)
- .Where(m => m.GetParameters().Length == 7)
- .Where(m => m.GetParameters()[0].ParameterType == typeof(IDbConnection))
- .Where(m => m.GetParameters()[1].ParameterType == typeof(string))
- .Where(m => m.GetParameters()[2].ParameterType == typeof(object))
- .Where(m => m.GetParameters()[3].ParameterType == typeof(IDbTransaction))
- .Where(m => m.GetParameters()[4].ParameterType == typeof(bool))
- .Where(m => m.GetParameters()[5].ParameterType == typeof(int?))
- .Where(m => m.GetParameters()[6].ParameterType == typeof(CommandType?))
- .Where(m => m.ContainsGenericParameters)
- .Single();
- // создать сконструированный метод SqlMapper.Query<itemType>(IDbConnection, string, object, IDbTransaction, bool, int?, CommandType?)
- MethodInfo constructed_method = generic_method.MakeGenericMethod(new Type[] { itemType });
- // строка запроса
- string oracleSelectAllTableRows = @"SELECT * FROM " + tableName + ' ' + sqlWhere;
- // формируем список параметров для вызова
- object[] call_parameters = new object[]
- {
- MNLZContext.oracleConnect,
- oracleSelectAllTableRows,
- constructed_method.GetParameters()[2].DefaultValue,
- constructed_method.GetParameters()[3].DefaultValue,
- constructed_method.GetParameters()[4].DefaultValue,
- constructed_method.GetParameters()[5].DefaultValue,
- constructed_method.GetParameters()[6].DefaultValue
- };
- // делаем вызов сконструированного метода, чтобы получить новый набор данных 'tableRows'
- // IEnumerable<itemType> tableRows = MNLZContext.oracleConnect.Query<itemType>(oracleSelectAllTableRows);
- // IEnumerable<itemType> tableRows = SqlMapper.Query<itemType>(MNLZContext.oracleConnect, oracleSelectAllTableRows[, null, null, true, null, null]);
- // поскольку вызывается статический метод, то первый параметр .Invoke() ставим 'null' (объекта нет)
- object tableRows = constructed_method.Invoke(null, call_parameters);
- // конструируем тип IEnumerable<itemType>
- Type ienumerableType = typeof(IEnumerable<>).MakeGenericType(new Type[] { itemType });
- // запрашиваем у типа таблицы ObservableCollection<itemType> подходящий конструктор
- ConstructorInfo constructor = tableType.GetConstructors()
- .Where(c => c.GetParameters().Length == 1)
- .Where(c => c.GetParameters()[0].ParameterType.IsEquivalentTo(ienumerableType))
- .Single();
- // конструируем и возвращаем коллекцию 'ObservableCollection<itemType>(tableRows)'
- return constructor.Invoke(new object[] { tableRows });
- }
- public void Prepare()
- {
- dbTables["test1"] = new ObservableCollection<LOGS>(Enumerable.Repeat(new LOGS(), 3));
- dbTables["test2"] = new ObservableCollection<TRACK_EVENT>(Enumerable.Repeat(new TRACK_EVENT(), 4));
- }
- public void PrintInfo(string tableName, string addition)
- {
- Console.WriteLine($" {addition}: dbTables[\"{tableName}\"]'s type is '{dbTables[tableName].GetType().Name}<{dbTables[tableName].GetType().GetGenericArguments()[0].Name}>'");
- if (dbTables[tableName] is ObservableCollection<LOGS> t_1)
- {
- Console.WriteLine($" {addition}: dbTables[\"{tableName}\"].Count = {t_1.Count}");
- Console.WriteLine($" {addition}: dbTables[\"{tableName}\"]'s item[0] type is '{t_1[0].GetType().Name}'");
- }
- else if (dbTables[tableName] is ObservableCollection<TRACK_EVENT> t_2)
- {
- Console.WriteLine($" {addition}: dbTables[\"{tableName}\"].Count = {t_2.Count}");
- Console.WriteLine($" {addition}: dbTables[\"{tableName}\"]'s item[0] type is '{t_2[0].GetType().Name}'");
- }
- else
- throw new Exception("Что-то поломалось в типах элементов 'dbTables[]'");
- }
- public void Test()
- {
- foreach (string tableName in dbTables.Keys.ToList())
- {
- Console.WriteLine($"key: '{tableName}'");
- PrintInfo(tableName, "old");
- dbTables[tableName] = getTableRows(tableName);
- PrintInfo(tableName, "new");
- }
- Console.WriteLine("==========");
- }
- static void Main(string[] args)
- {
- Solution test_object = new Solution();
- test_object.Prepare();
- test_object.Test();
- test_object.Test();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement