Exemplo n.º 1
0
        /// <summary>
        /// Inserts an entity into table "Ts" asynchronously using .NET 4.5 Task and returns identity id.
        /// </summary>
        /// <typeparam name="T">The type being inserted.</typeparam>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entityToInsert">Entity to insert</param>
        /// <param name="transaction">The transaction to run under, null (the default) if none</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <param name="sqlAdapter">The specific ISqlAdapter to use, auto-detected based on connection if null</param>
        /// <returns>Identity of inserted entity</returns>
        public static Task <int> InsertAsync <T>(this IDbConnection connection, T entityToInsert, IDbTransaction transaction = null,
                                                 int?commandTimeout = null, ISqlAdapter sqlAdapter = null) where T : class
        {
            var type = typeof(T);

            sqlAdapter = sqlAdapter ?? GetFormatter(connection);

            var isList = false;

            if (type.IsArray)
            {
                isList = true;
                type   = type.GetElementType();
            }
            else if (type.IsGenericType)
            {
                var  typeInfo = type.GetTypeInfo();
                bool implementsGenericIEnumerableOrIsGenericIEnumerable =
                    typeInfo.ImplementedInterfaces.Any(ti => ti.IsGenericType && ti.GetGenericTypeDefinition() == typeof(IEnumerable <>)) ||
                    typeInfo.GetGenericTypeDefinition() == typeof(IEnumerable <>);

                if (implementsGenericIEnumerableOrIsGenericIEnumerable)
                {
                    isList = true;
                    type   = type.GetGenericArguments()[0];
                }
            }

            var name               = GetTableName(type);
            var sbColumnList       = new StringBuilder(null);
            var allProperties      = TypePropertiesCache(type);
            var keyProperties      = KeyPropertiesCache(type).ToList();
            var computedProperties = ComputedPropertiesCache(type);
            var allPropertiesExceptKeyAndComputed = allProperties.Except(keyProperties.Union(computedProperties)).ToList();

            for (var i = 0; i < allPropertiesExceptKeyAndComputed.Count; i++)
            {
                var property = allPropertiesExceptKeyAndComputed[i];
                sqlAdapter.AppendColumnName(sbColumnList, property.Name);
                if (i < allPropertiesExceptKeyAndComputed.Count - 1)
                {
                    sbColumnList.Append(", ");
                }
            }

            var sbParameterList = new StringBuilder(null);

            for (var i = 0; i < allPropertiesExceptKeyAndComputed.Count; i++)
            {
                var property = allPropertiesExceptKeyAndComputed[i];
                sbParameterList.AppendFormat("@{0}", property.Name);
                if (i < allPropertiesExceptKeyAndComputed.Count - 1)
                {
                    sbParameterList.Append(", ");
                }
            }

            if (!isList)    //single entity
            {
                return(sqlAdapter.InsertAsync(connection, transaction, commandTimeout, name, sbColumnList.ToString(),
                                              sbParameterList.ToString(), keyProperties, entityToInsert));
            }

            //insert list of entities
            var cmd = $"INSERT INTO {name} ({sbColumnList}) values ({sbParameterList})";

            return(connection.ExecuteAsync(cmd, entityToInsert, transaction, commandTimeout));
        }
Exemplo n.º 2
0
 public static void SetAdapter(SqlAdapter adapter)
 {
     _defaultAdapter = GetAdapterInstance(adapter);
 }
Exemplo n.º 3
0
        public static void Register(Type connectionType, ISqlAdapter adapter)
        {
            var adapterKey = connectionType.Name.ToLower();

            AdapterDictionary[adapterKey] = adapter;
        }
Exemplo n.º 4
0
 public BooleanMemberExpressionVisitor(bool?nonParametric, Dictionary <string, object> parameters, ISqlAdapter sqlAdapter) : base(nonParametric, parameters, sqlAdapter)
 {
 }
Exemplo n.º 5
0
 public QueryBody(ISqlAdapter sqlAdapter)
 {
     _sqlAdapter = sqlAdapter;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlAccountRepository"/> class.
 /// </summary>
 /// <param name="sqlAdapter">Used to modify SQL to vendor specific statements.</param>
 public SqlAccountRepository(ISqlAdapter sqlAdapter)
 {
     _sqlAdapter = sqlAdapter;
 }
        public static (string, Dictionary <string, object>) ToWhereClause <T>(this Expression <Func <T, bool> > expression, bool?nonParametric = null, ISqlAdapter sqlAdapter = null) where T : class
        {
            ExpressionEntry expressionEntry = new ExpressionEntry(nonParametric ?? ExpressionConfigurations.NonParametric, sqlAdapter ?? ExpressionConfigurations.Adapter);

            expressionEntry.Visit(expression);

            return(expressionEntry.GetResult());
        }
Exemplo n.º 8
0
        public static long Insert <T>(this IDbConnection connection, T entityToInsert, IDbTransaction transaction = null, int?commandTimeout = default(int?)) where T : class
        {
            bool flag = false;
            Type type = typeof(T);

            if (type.IsArray)
            {
                flag = true;
                type = type.GetElementType();
            }
            else if (type.IsGenericType())
            {
                flag = true;
                type = type.GetGenericArguments()[0];
            }
            string              tableName     = GetTableName(type);
            StringBuilder       stringBuilder = new StringBuilder(null);
            List <PropertyInfo> first         = TypePropertiesCache(type);
            List <PropertyInfo> list          = KeyPropertiesCache(type);
            List <PropertyInfo> second        = ComputedPropertiesCache(type);
            List <PropertyInfo> list2         = first.Except(list.Union(second)).ToList();
            ISqlAdapter         formatter     = GetFormatter(connection);

            for (int i = 0; i < list2.Count; i++)
            {
                PropertyInfo propertyInfo = list2.ElementAt(i);
                formatter.AppendColumnName(stringBuilder, propertyInfo.Name);
                if (i < list2.Count - 1)
                {
                    stringBuilder.Append(", ");
                }
            }
            StringBuilder stringBuilder2 = new StringBuilder(null);

            for (int j = 0; j < list2.Count; j++)
            {
                PropertyInfo propertyInfo2 = list2.ElementAt(j);
                stringBuilder2.AppendFormat("@{0}", propertyInfo2.Name);
                if (j < list2.Count - 1)
                {
                    stringBuilder2.Append(", ");
                }
            }
            bool num = connection.State == ConnectionState.Closed;

            if (num)
            {
                connection.Open();
            }
            int num2;

            if (!flag)
            {
                num2 = formatter.Insert(connection, transaction, commandTimeout, tableName, stringBuilder.ToString(), stringBuilder2.ToString(), list, entityToInsert);
            }
            else
            {
                string text = string.Format("insert into {0} ({1}) values ({2})", tableName, stringBuilder, stringBuilder2);
                num2 = SqlMapper.Execute(connection, text, (object)entityToInsert, transaction, commandTimeout, (CommandType?)null);
            }
            if (num)
            {
                connection.Close();
            }
            return(num2);
        }
Exemplo n.º 9
0
 /// <summary>
 /// InsertAsync
 /// </summary>
 /// <param name="model"></param>
 /// <param name="transaction"></param>
 /// <param name="commandTimeout"></param>
 /// <param name="sqlAdapter"></param>
 /// <returns>Identity of inserted entity</returns>
 public async virtual Task <int> InsertAsync(T model, IDbTransaction transaction = null, int?commandTimeout = null, ISqlAdapter sqlAdapter = null)
 {
     using (var conn = new MySqlConnection(_connStr))
     {
         conn.Open();
         return(await conn.InsertAsync(model, transaction, commandTimeout, sqlAdapter));
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlAccountRepository"/> class.
 /// </summary>
 /// <param name="sqlAdapter">Used to modify SQL to vendor specific statements.</param>
 public SqlAccountRepository(ISqlAdapter sqlAdapter)
 {
     _sqlAdapter = sqlAdapter;
 }
 public BaseExpressionVisitor(bool?nonParametric, Dictionary <string, object> parameters, ISqlAdapter sqlAdapter)
 {
     sb            = new StringBuilder();
     NonParametric = nonParametric;
     Parameters    = parameters;
     SqlAdapter    = sqlAdapter;
 }
Exemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dbOptions"></param>
        /// <param name="options"></param>
        /// <param name="sqlAdapter">数据库适配器</param>
        /// <param name="loggerFactory">日志工厂</param>
        /// <param name="loginInfo">登录信息</param>
        protected DbContextOptionsAbstract(DbOptions dbOptions, DbConnectionOptions options, ISqlAdapter sqlAdapter, ILoggerFactory loggerFactory, ILoginInfo loginInfo)
        {
            if (options.Name.IsNull())
            {
                throw new ArgumentNullException(nameof(options.Name), "数据库连接名称未配置");
            }

            if (options.ConnString.IsNull())
            {
                throw new ArgumentNullException(nameof(options.ConnString), "数据库连接字符串未配置");
            }

            DbOptions        = dbOptions;
            Name             = options.Name;
            ConnectionString = options.ConnString;
            SqlAdapter       = sqlAdapter;
            LoggerFactory    = loggerFactory;
            LoginInfo        = loginInfo;

            if (options.EntityTypes != null && options.EntityTypes.Any())
            {
                foreach (var entityType in options.EntityTypes)
                {
                    EntityDescriptorCollection.Add(new EntityDescriptor(entityType, sqlAdapter, new EntitySqlBuilder()));
                }
            }
        }
 public DbContextOptionsBuilder UseSqlAdapter(ISqlAdapter sqlAdapter)
 {
     _sqlAdapter = sqlAdapter;
     return(this);
 }
Exemplo n.º 14
0
        /// <summary>
        /// Inserts an entity into table "Ts" and returns identity id.
        /// </summary>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entityToInsert">Entity to insert</param>
        /// <returns>Identity of inserted entity</returns>
        public static long Insert <T>(this IDbConnection connection, T entityToInsert, IDbTransaction transaction = null, int?commandTimeout = null, ISqlAdapter adapter = null) where T : class
        {
            var type               = typeof(T);
            var name               = GetTableName(type);
            var sbColumnList       = new StringBuilder(null);
            var allProperties      = TypePropertiesCache(type);
            var keyProperties      = KeyPropertiesCache(type);
            var computedProperties = ComputedPropertiesCache(type);
            var allPropertiesExceptKeyAndComputed = allProperties.Except(keyProperties.Union(computedProperties)).ToList();

            for (var i = 0; i < allPropertiesExceptKeyAndComputed.Count(); i++)
            {
                var property = allPropertiesExceptKeyAndComputed.ElementAt(i);
                sbColumnList.AppendFormat("[{0}]", property.Name);
                if (i < allPropertiesExceptKeyAndComputed.Count() - 1)
                {
                    sbColumnList.Append(", ");
                }
            }

            var sbParameterList = new StringBuilder(null);

            for (var i = 0; i < allPropertiesExceptKeyAndComputed.Count(); i++)
            {
                var property = allPropertiesExceptKeyAndComputed.ElementAt(i);
                sbParameterList.AppendFormat("@{0}", property.Name);
                if (i < allPropertiesExceptKeyAndComputed.Count() - 1)
                {
                    sbParameterList.Append(", ");
                }
            }

            if (adapter == null)
            {
                adapter = GetFormatter(connection);
            }
            return(adapter.Insert(connection, transaction, commandTimeout, name, sbColumnList.ToString(),
                                  sbParameterList.ToString(), keyProperties, entityToInsert));
        }
 internal SqlQueryBuilder(string tableName, ISqlAdapter adapter)
 {
     _tableNames.Add(tableName);
     Adapter = adapter;
     Parameters = new ExpandoObject();
     _paramIndex = 0;
 }
Exemplo n.º 16
0
 public ExpressionResolver(ISqlAdapter sqlAdapter, QueryBody queryBody)
 {
     _sqlAdapter = sqlAdapter;
     _queryBody  = queryBody;
 }
Exemplo n.º 17
0
 public SqlGenerator(ISqlAdapter adapter)
 {
     this.adapter = adapter;
 }
Exemplo n.º 18
0
 public DbContextOptions(string connectionString, ISqlAdapter sqlAdapter)
 {
     ConnectionString = connectionString;
     SqlAdapter       = sqlAdapter;
 }
Exemplo n.º 19
0
 public static void SetAdapter(SqlAdapter adapter)
 {
     _defaultAdapter = GetAdapterInstance(adapter);
 }
 public static string ToWhereClauseNonParametric <T>(this Expression <Func <T, bool> > expression, ISqlAdapter sqlAdapter = null) where T : class
 {
     return(ToWhereClause(expression, true, sqlAdapter).Item1);
 }