Add dynamic SQL execution to IRecDbContext interface
Added Database property to IRecDbContext for database operations. Introduced ExecuteDynamicSqlAsync extension method to run arbitrary SQL and return results as JSON. This enables flexible querying and result serialization.
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using ReC.Domain.QueryOutput;
|
||||
using ReC.Domain.Views;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ReC.Application.Common.Interfaces;
|
||||
|
||||
@@ -21,4 +23,38 @@ public interface IRecDbContext
|
||||
#endregion DbSets
|
||||
|
||||
public Task<int> SaveChangesAsync(CancellationToken cancel = default);
|
||||
|
||||
public DatabaseFacade Database { get; }
|
||||
}
|
||||
|
||||
public static class RecDbContextSaveExtensions
|
||||
{
|
||||
public static async Task<string> ExecuteDynamicSqlAsync(this IRecDbContext context, string sql)
|
||||
{
|
||||
var result = new List<Dictionary<string, object?>>();
|
||||
|
||||
using var command = context.Database.GetDbConnection().CreateCommand();
|
||||
|
||||
command.CommandText = sql;
|
||||
|
||||
await context.Database.OpenConnectionAsync();
|
||||
|
||||
using var reader = await command.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
var row = new Dictionary<string, object?>();
|
||||
|
||||
for (int i = 0; i < reader.FieldCount; i++)
|
||||
{
|
||||
var columnName = reader.GetName(i);
|
||||
var value = reader.IsDBNull(i) ? null : reader.GetValue(i);
|
||||
|
||||
row[columnName] = value;
|
||||
}
|
||||
|
||||
result.Add(row);
|
||||
}
|
||||
|
||||
return JsonSerializer.Serialize(result);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user