public static async Task <object> ExecuteScalarAsync(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); object val = await cmd.ExecuteScalarAsync(); cmd.Parameters.Clear(); return(val); }
public async Task <bool> AddRecord_Async(IDataEntity Record) { OnBeforeInsert(new OperatorEventArguments() { Data = Record }); DataInterface.Attribbutes.NotInsert NotInsertAttribute = (DataInterface.Attribbutes.NotInsert)(from attr in Record.GetType().GetCustomAttributes(true) where attr.GetType() == typeof(DataInterface.Attribbutes.NotInsert) select attr).FirstOrDefault(); if (NotInsertAttribute != null) { throw new Exception("A Class marked with attribute NotInsert cannot perform write opperations"); } //first find the table attribute to obtain the maped db table DataInterface.Attribbutes.Table TableAttribute = (DataInterface.Attribbutes.Table)(from attr in Record.GetType().GetCustomAttributes(true) where attr.GetType() == typeof(DataInterface.Attribbutes.Table) select attr).FirstOrDefault(); using (MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(this.Source)) { connection.Open(); try { StringBuilder Query = new StringBuilder(); if (TableAttribute != null) { Query.Append($"Insert INTO {TableAttribute.Name} ("); } else { Query.Append($"Insert INTO {Record.GetType().Name} ("); } //get the properties of the entity List <PropertyInfo> properties = Record.GetType().GetProperties().ToList(); Dictionary <string, string> FieldsNames = new Dictionary <string, string>(); List <string> FieldsHolders = new List <string>(); // create the insert query CreateInsertQuery(Record, Query, properties, FieldsNames); var com = new MySql.Data.MySqlClient.MySqlCommand(Query.ToString(), connection); //Create the sql parameters if (_Encryptor != null) { if (Record is IEncryptableClass) { _Encryptor.EncryptProperties((IEncryptableClass)Record); } } SetInsetParameters(Record, properties, FieldsNames, com); int result = Convert.ToInt32(await com.ExecuteScalarAsync()); //find the Key property of the entity UpdateKeyPropery(Record, properties, result); if (_Encryptor != null) { if (Record is IEncryptableClass) { _Encryptor.Decryptproperties((IEncryptableClass)Record); } } connection.Close(); } catch (Exception ex) { if (connection.State == System.Data.ConnectionState.Open) { connection.Close(); } OnRecordInsertFailed(new OperatorEventArguments() { Data = Record }); return(false); } } OnRecordInserted(new OperatorEventArguments() { Data = Record }); return(true); }