/// <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, bool isRowEffected = false,
                                                 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())
            {
                isList = true;
                type   = type.GetGenericArguments()[0];
            }

            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[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, isRowEffected));
            }

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

            return(connection.ExecuteAsync(cmd, entityToInsert, transaction, commandTimeout));
        }
        /// <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);
            var isList = false;

            sqlAdapter = sqlAdapter ?? GetFormatter(connection);
            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, GetColumnName(property), "");
                if (i < allPropertiesExceptKeyAndComputed.Count - 1)
                {
                    sbColumnList.Append(", ");
                }
            }

            var sbParameterList = new StringBuilder(null);

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

            return(sqlAdapter.InsertAsync(connection, transaction, commandTimeout, name, sbColumnList.ToString(),
                                          sbParameterList.ToString(), keyProperties, entityToInsert, isList));
        }
示例#3
0
        /// <summary>
        /// Inserts an entity into table "Ts" asynchronously using .NET 4.5 Task 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 async Task <int> InsertAsync <T>(this IDbConnection connection, T entityToInsert, IDbTransaction transaction = null,
                                                       int?commandTimeout = null, ISqlAdapter sqlAdapter = null) where T : class
        {
            var isList = false;

            var type = typeof(T);

            if (type.IsArray || type.IsGenericType)
            {
                isList = true;
                type   = type.GetGenericArguments()[0];
            }

            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 (!isList)    //single entity
            {
                if (sqlAdapter == null)
                {
                    sqlAdapter = GetFormatter(connection);
                }
                return(await sqlAdapter.InsertAsync(connection, transaction, commandTimeout, name, sbColumnList.ToString(),
                                                    sbParameterList.ToString(), keyProperties, entityToInsert));
            }

            //insert list of entities
            var cmd = String.Format("insert into {0} ({1}) values ({2})", name, sbColumnList, sbParameterList);

            return(await connection.ExecuteAsync(cmd, entityToInsert, transaction, commandTimeout));
        }
        /// <summary>
        /// Inserts an entity into table "Ts" asynchronously using .NET 4.5 Task 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 Task <int> InsertAsync <T>(this IDbConnection connection, T entityToInsert, IDbTransaction transaction = null, int?commandTimeout = 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(computedProperties);
            var autoIncrementProperties           = AutoIncrementPropertiesCache(type);
            var hasAutoIncrement = false;

            if (autoIncrementProperties.Any() && keyProperties.Any())
            {
                hasAutoIncrement = keyProperties.Contains(autoIncrementProperties.First());
            }
            if (hasAutoIncrement)
            {
                allPropertiesExceptKeyAndComputed = allProperties.Except(keyProperties.Union(computedProperties));
            }
            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(", ");
                }
            }
            ISqlAdapter adapter = GetFormatter(connection);

            return(adapter.InsertAsync(connection, transaction, commandTimeout, name, sbColumnList.ToString(), sbParameterList.ToString(), keyProperties, entityToInsert, hasAutoIncrement));
        }
        /// <summary>
        /// Inserts an entity into table "Ts" asynchronously using .NET 4.5 Task and returns identity id.
        /// </summary>
        /// <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);

            if (sqlAdapter == null)
            {
                sqlAdapter = GetFormatter(connection);
            }

            var isList = false;

            if (type.IsArray)
            {
                isList = true;
                type   = type.GetElementType();
            }
            else if (type.IsGenericType())
            {
                isList = true;
                type   = type.GetGenericArguments()[0];
            }

            var name               = GetTableName(type);
            var sbColumnList       = new StringBuilder(null);
            var allProperties      = TypePropertiesCache(type);
            var keyProperties      = KeyPropertiesCache(type);
            var computedProperties = ComputedPropertiesCache(type);
            var exceptProperties   = computedProperties;

            if (!(keyProperties.Count == 1 && (keyProperties.First().PropertyType == typeof(Guid) || keyProperties.First().PropertyType == typeof(string))))
            {
                exceptProperties = keyProperties.Union(computedProperties).ToList();
            }
            var allPropertiesExceptKeyAndComputed = allProperties.Except(exceptProperties).ToList();

            var keyPropert = keyProperties.FirstOrDefault();

            if (keyPropert != null)
            {
                //当未使用Id为主键时 新增的时候 排除Id
                if (keyPropert.Name.ToLower() != "id")
                {
                    allPropertiesExceptKeyAndComputed = allPropertiesExceptKeyAndComputed.Where(p => p.Name.ToLower() != "id").ToList();
                }
            }

            for (var i = 0; i < allPropertiesExceptKeyAndComputed.Count; i++)
            {
                var property = allPropertiesExceptKeyAndComputed.ElementAt(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.ElementAt(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));
        }
        /// <summary>
        /// Inserts an entity into table "Ts" asynchronously using 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 async 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.ToList();//.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(", ");
                }
            }

            int returnVal = 0;
            var wasClosed = connection.State == ConnectionState.Closed;

            if (wasClosed)
            {
                connection.Open();
            }

            if (!isList)    //single entity
            {
                returnVal = await sqlAdapter.InsertAsync(connection, transaction, commandTimeout, name, sbColumnList.ToString(),
                                                         sbParameterList.ToString(), keyProperties, entityToInsert);
            }
            else
            {
                //insert list of entities
                var cmd = $"insert into {name} ({sbColumnList}) values ({sbParameterList})";
                returnVal = await connection.ExecuteAsync(cmd, entityToInsert, transaction, commandTimeout);
            }
            if (wasClosed)
            {
                connection.Close();
            }
            return(returnVal);
        }