- Change from FirstOrDefaultAsync to ToListAsync + FirstOrDefault - Ensures proper query execution for both EF6 (.NET Framework 4.8) and EF Core (.NET 8.0) - Prevents potential query execution issues - Add using System.Linq directive
58 lines
1.8 KiB
C#
58 lines
1.8 KiB
C#
#if NET48
|
|
using System.Data.Entity;
|
|
#else
|
|
using Microsoft.EntityFrameworkCore;
|
|
#endif
|
|
using ECMJobRunner.Application.Common.Interfaces;
|
|
using ECMJobRunner.Infrastructure.Data;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using System.Linq;
|
|
|
|
namespace ECMJobRunner.Infrastructure.Services
|
|
{
|
|
/// <summary>
|
|
/// Entity Framework implementation of ISQLExecutor
|
|
/// Executes raw SQL queries and maps results to DTOs
|
|
/// </summary>
|
|
public class SQLExecutor : ISQLExecutor
|
|
{
|
|
private readonly JobRunnerDbContext _context;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of SQLExecutor
|
|
/// </summary>
|
|
/// <param name="context">The database context</param>
|
|
public SQLExecutor(JobRunnerDbContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Executes a SQL query and maps the result to the specified type
|
|
/// </summary>
|
|
/// <typeparam name="TResult">The type to map the query result to</typeparam>
|
|
/// <param name="sql">The SQL query to execute</param>
|
|
/// <param name="cancellationToken">Cancellation token</param>
|
|
/// <returns>The mapped result or null if no result</returns>
|
|
public async Task<TResult?> ExecuteQueryAsync<TResult>(string sql, CancellationToken cancellationToken = default)
|
|
{
|
|
#if NET48
|
|
// Entity Framework 6 implementation
|
|
var result = await _context.Database
|
|
.SqlQuery<TResult>(sql)
|
|
.ToListAsync(cancellationToken);
|
|
|
|
return result.FirstOrDefault();
|
|
#else
|
|
// Entity Framework Core implementation
|
|
var result = await _context.Database
|
|
.SqlQueryRaw<TResult>(sql)
|
|
.ToListAsync(cancellationToken);
|
|
|
|
return result.FirstOrDefault();
|
|
#endif
|
|
}
|
|
}
|
|
}
|