I am trying to execute a query on our database, I've created it in text because I cannot make it efficiently enough in Entity Framework Core.
This is the code i am using but it seems like it is not being executed on the database (i see no record of this transaction on the database) but i also get no errors. What am I doing wrong?
public async Task<CleanupObservationsResponse> Handle(CleanupObservationsCommand request, CancellationToken cancellationToken)
{
var removalDate = DateTime.Now.AddMonths(-3);
_logger.LogInformation($"Started cleaning up observations for all observations before {removalDate.Date.ToString("yyyy-MM-dd")}");
await _observationRepository.CleanupObservations(removalDate);
}
public Task<bool> CleanupObservations(DateTime removalDate)
{
var sql = $"START TRANSACTION;" +
$"SET @RemovalDate := \"{removalDate.ToString("yyyy-MM-dd")}\";" +
$"# MySql Variables can only store 1 row and thus the results of this query cannot be saved in a variable." +
$"# SET @observationsToDelete := (SELECT Identification FROM cpp.Observation WHERE StartedUtc < @RemovalDate);" +
$"DELETE FROM PropertyValues WHERE ObservationIdentification IN(SELECT Identification FROM Observation WHERE StartedUtc < @RemovalDate);" +
$"DELETE FROM HoldReasonObservation WHERE ObservationIdentification IN(SELECT Identification FROM Observation WHERE StartedUtc < @RemovalDate);" +
$"DELETE FROM ObservationDeviation WHERE ObservationIdentification IN(SELECT Identification FROM Observation WHERE StartedUtc < @RemovalDate);" +
$"DELETE FROM ObservationQRTokens WHERE ObservationIdentification IN(SELECT Identification FROM Observation WHERE StartedUtc < @RemovalDate);" +
$"DELETE FROM ObservationTarra WHERE ObservationIdentification IN(SELECT Identification FROM Observation WHERE StartedUtc < @RemovalDate);" +
$"DELETE FROM Alibi WHERE ObservationIdentification IN(SELECT Identification FROM Observation WHERE StartedUtc < @RemovalDate);" +
$"DELETE FROM PackageTrackingIdentifications WHERE ObservationIdentification IN(SELECT Identification FROM Observation WHERE StartedUtc < @RemovalDate);" +
$"DELETE FROM QuestionAnswer WHERE ObservationIdentification IN(SELECT Identification FROM Observation WHERE StartedUtc < @RemovalDate);" +
$"DELETE FROM Observation WHERE StartedUtc < @RemovalDate;" +
$"COMMIT;";
return this.ExecuteSQL(sql);
}
private async Task<bool> ExecuteSQL(string sql)
{
var connection = Context.Database.GetDbConnection();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
return await cmd.ExecuteNonQueryAsync() > 0;
}
}