public async Task<bool> Exists(IHomeModel model, QueryType queryType) { return await Task.Run(async () => { bool exists = true; string qt = Enum.GetName(typeof(QueryType), queryType); using (SqlConnection con = new SqlConnection(await GetConnectionString())) { con.Open(); using ( SqlCommand command = new SqlCommand( string.Format("if (EXISTS (SELECT [Id] FROM [dbo].[Entry] WHERE [{0}] = @{0})) SELECT 'true' ELSE SELECT 'false'", qt), con)) { command.Parameters.Add(new SqlParameter() { ParameterName = qt, Value = model.GetType().GetProperty(qt).GetValue(model, null) }); using (SqlDataReader reader = await command.ExecuteReaderAsync()) { while (reader.Read()) { exists = bool.Parse(reader.GetString(0)); } return exists; } } } }); }
public async Task DeleteEntry(IHomeModel model, QueryType queryType) { await Task.Run(async () => { string qt = Enum.GetName(typeof(QueryType), queryType); using (SqlConnection con = new SqlConnection(await GetConnectionString())) { con.Open(); using (SqlCommand command = new SqlCommand(string.Format("DELETE FROM [dbo].[Entry] WHERE [{0}] = @{0};", qt), con)) { command.Parameters.Add(new SqlParameter() { ParameterName = qt, Value = model.GetType().GetProperty(qt).GetValue(model, null) }); await command.ExecuteNonQueryAsync(); } } }); }
public async Task<string> GetEntry(IHomeModel model, QueryType queryType) { return await Task.Run(async () => { string valueType = Enum.GetName(typeof(QueryType), queryType); string filterType = GetFilterType(queryType); using (SqlConnection con = new SqlConnection(await GetConnectionString())) { con.Open(); using (SqlCommand command = new SqlCommand(string.Format("SELECT [{0}] FROM [dbo].[Entry] WHERE [{1}] = @{1}", valueType, filterType), con)) { command.Parameters.Add(new SqlParameter() { ParameterName = filterType, Value = model.GetType().GetProperty(filterType).GetValue(model, null) }); using (SqlDataReader reader = await command.ExecuteReaderAsync()) { while (reader.Read()) { return reader.GetString(0); } throw new Exception(string.Format("{0} {1} not found in database.", filterType, valueType)); } } } }); }