#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
{
///
/// Entity Framework implementation of ISQLExecutor
/// Executes raw SQL queries and maps results to DTOs
///
public class SQLExecutor : ISQLExecutor
{
private readonly JobRunnerDbContext _context;
///
/// Initializes a new instance of SQLExecutor
///
/// The database context
public SQLExecutor(JobRunnerDbContext context)
{
_context = context;
}
///
/// Executes a SQL query and maps the result to the specified type
///
/// The type to map the query result to
/// The SQL query to execute
/// Cancellation token
/// The mapped result or null if no result
public async Task ExecuteQueryAsync(string sql, CancellationToken cancellationToken = default)
{
#if NET48
// Entity Framework 6 implementation
var result = await _context.Database
.SqlQuery(sql)
.ToListAsync(cancellationToken);
return result.FirstOrDefault();
#else
// Entity Framework Core implementation
var result = await _context.Database
.SqlQueryRaw(sql)
.ToListAsync(cancellationToken);
return result.FirstOrDefault();
#endif
}
}
}