【发布时间】:2020-09-14 07:16:15
【问题描述】:
我正在尝试对我们的数据库执行查询,我已在文本中创建它,因为我无法在 Entity Framework Core 中使其足够高效。
这是我正在使用的代码,但它似乎没有在数据库上执行(我在数据库上没有看到此交易的记录),但我也没有收到任何错误。我做错了什么?
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;
}
}
【问题讨论】:
-
你应该等待 this.ExecuteSQL(sql);
-
@Ayoub_B 是的,我意识到我没有包含该代码,我在调用堆栈中执行了 1 个方法(现在也将其添加到问题中)
-
你能不能试着把它包装在一个try-catch中,也许会抛出一个异常但它被吞噬了
-
堆栈中有一个更高的尝试追赶,它总是会记录它,但我可以尝试
-
不,仍然没有错误。