/// <summary> /// Insert object to table and populates key properties with generated values from database /// </summary> /// <typeparam name="T">type of object</typeparam> /// <param name="conn">A connection</param> /// <param name="data">Object containing the data</param> /// <param name="transaction">Transaction to associate with the command</param> /// <returns>Rows affected</returns> public static int Insert <T>(this IDbConnection conn, T data, IDbTransaction transaction = null) where T : class { TypeDescriber td = TypeHandler.Get <T>(); IEnumerable <PropertyDescriber> generated = td.Generated; if (generated.Count() > 0) { string columns = td.WriteableColumns.Select(x => x.DbName).Aggregate((a, b) => a + "," + b); string values = td.WriteableColumns.Select(x => "@" + x.Property.Name).Aggregate((a, b) => a + "," + b); string returns = string.Join(",", generated.Select(x => x.DbName)); string sql = $"INSERT INTO {td.Table} ({columns}) VALUES ({values}) RETURNING {returns}"; var result = conn.QueryAssoc(sql, data, transaction).FirstOrDefault(); foreach (var prop in generated) { td.SetValue(prop.Property.Name, data, result[prop.DbName]); } return(1); } else { return(conn.Insert(td.Table, data, transaction)); } }
/// <summary> /// Insert object in table. Will populate generated fields with values from database. /// </summary> /// <typeparam name="T">type of object</typeparam> /// <param name="conn">A connection</param> /// <param name="data">Object containing the data</param> /// <param name="transaction">Transaction to associate with the command</param> /// <param name="cancellationToken">Cancellationtoken</param> /// <returns>Rows affected</returns> public static async Task <int> InsertAsync <T>(this DbConnection conn, T data, DbTransaction transaction = null, CancellationToken cancellationToken = default) where T : class { TypeDescriber td = TypeHandler.Get <T>(); IEnumerable <PropertyDescriber> generated = td.Generated; if (generated.Count() > 0) { string columns = td.WriteableColumns.Select(x => x.DbName).Aggregate((a, b) => a + "," + b); string values = td.WriteableColumns.Select(x => "@" + x.Property.Name).Aggregate((a, b) => a + "," + b); string returns = string.Join(",", generated.Select(x => x.DbName)); string sql = $"INSERT INTO {td.Table} ({columns}) VALUES ({values}) RETURNING {returns}"; var result = (await conn.QueryAssocAsync(sql, data, transaction, cancellationToken).FirstOrDefaultAsync().ConfigureAwait(false)); foreach (var prop in generated) { td.SetValue(prop.Property.Name, data, result[prop.DbName]); } return(1); } else { return(await conn.InsertAsync(td.Table, data, transaction, cancellationToken).ConfigureAwait(false)); } }