/// <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)); }
public static string getCmdInsert(ISqlAdapter adapter, ICollection <KeyValuePair <string, Object> > entityToInsert, string tableName, string keyProperties = null) { var sbColumnList = new StringBuilder(null); var sbParameterList = new StringBuilder(null); var index = 0; foreach (var item in entityToInsert) { var property = (KeyValuePair <string, object>)item; // if (!string.IsNullOrEmpty(keyProperties) && property.Key.ToUpper() == keyProperties.ToUpper()) { continue; } else { index++; } // Column adapter.AppendColumnName(sbColumnList, property.Key); if (index < entityToInsert.Count) { sbColumnList.Append(","); } // Parameter adapter.AppendParametr(sbParameterList, property.Key); if (index < entityToInsert.Count) { sbParameterList.Append(","); } } var cmd = $"insert into {tableName} ({sbColumnList.ToString().Trim(',')}) values ({sbParameterList.ToString().Trim(',')})"; return(cmd); }
/// <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)); }
/// <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); }
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); }