/// <summary> /// Updates an entity. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="connection">Open DbConnection</param> /// <param name="entity">The updated entity.</param> /// <returns>True if updated. Otherwise false.</returns> public static async Task <bool> Update <TEntity>(this DbConnection connection, TEntity entity) { var type = typeof(TEntity); var name = AttributeParser.GetTableName(type); var properties = AttributeParser.GetAllProperties(type); var collections = AttributeParser.GetAllCollections(type); var key = AttributeParser.GetKey(type); var keyColumn = AttributeParser.GetColumnName(key); var updateAttributes = properties.Except(collections).Except(AttributeParser.GetAllIgnored(type)).Where(pi => pi != key).ToList(); var sql = new StringBuilder($"UPDATE {name} SET "); for (var i = 0; i < updateAttributes.Count; i++) { sql.Append($"{AttributeParser.GetColumnName(updateAttributes[i])} = @{updateAttributes[i].Name}"); if (i < updateAttributes.Count - 1) { sql.Append(", "); } } sql.Append($" WHERE {keyColumn} = @{key.Name}"); var updated = await connection.Execute(sql.ToString(), entity).ConfigureAwait(false); return(updated > 0); }
/// <summary> /// Inserts an entity and returns an id. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="connection">Open DbConnection</param> /// <param name="entity">The new entity.</param> /// <returns>Id of inserted entity</returns> public static async Task <int> Insert <TEntity>(this DbConnection connection, TEntity entity) { var type = typeof(TEntity); var name = AttributeParser.GetTableName(type); var properties = AttributeParser.GetAllProperties(type); var collections = AttributeParser.GetAllCollections(type); var key = AttributeParser.GetKey(type); if (AttributeParser.GetKeyIsGenerated(key)) { properties = properties.Where(pi => pi != key); } var insertAttributes = properties.Except(collections).Except(AttributeParser.GetAllIgnored(type)).ToList(); var columns = new StringBuilder(null); for (var i = 0; i < insertAttributes.Count; i++) { columns.Append(AttributeParser.GetColumnName(insertAttributes[i])); if (i < insertAttributes.Count - 1) { columns.Append(", "); } } var parameters = new StringBuilder(null); for (var i = 0; i < insertAttributes.Count; i++) { parameters.Append($"@{insertAttributes[i].Name}"); if (i < insertAttributes.Count - 1) { parameters.Append(", "); } } var sql = $"INSERT INTO {name} ({columns}) VALUES ({parameters})"; await connection.Execute(sql, entity).ConfigureAwait(false); DbCommand command = connection.CreateCommand(); command.CommandText = "SELECT last_insert_rowid()"; var identity = await command.ExecuteScalarAsync().ConfigureAwait(false); return(Convert.ToInt32(identity, CultureInfo.InvariantCulture)); }