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.
60 lines
1.7 KiB
C#
60 lines
1.7 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
|
using ReC.Domain.QueryOutput;
|
|
using ReC.Domain.Views;
|
|
using System.Text.Json;
|
|
|
|
namespace ReC.Application.Common.Interfaces;
|
|
|
|
public interface IRecDbContext
|
|
{
|
|
#region DbSets
|
|
public DbSet<RecActionView> RecActionViews { get; set; }
|
|
|
|
public DbSet<ProfileView> ProfileViews { get; set; }
|
|
|
|
public DbSet<ResultView> RecResultViews { get; set; }
|
|
|
|
public DbSet<HeaderQueryResult> HeaderQueryResults { get; set; }
|
|
|
|
public DbSet<BodyQueryResult> BodyQueryResults { get; set; }
|
|
|
|
public DbSet<InsertObjectResult> RecResults { get; set; }
|
|
#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);
|
|
}
|
|
} |