using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
public static void Main()
var reportRepo = new ReportRepository();
var result = reportRepo.GetReport("VwExampleReport1");
Console.WriteLine("{0}", result.Columns[0]);
public class VwExampleReport1
public int VwExampleReport1Id { get; set; }
public class VwExampleReport2
public int VwExampleReport2Id { get; set; }
public partial class ReportContext : DbContext
public ReportContext(DbContextOptions<ReportContext> options) : base(options)
public virtual DbSet<VwExampleReport1> VwExampleReport1 { get; set; }
public virtual DbSet<VwExampleReport2> VwExampleReport2 { get; set; }
public abstract record Report()
public sealed record VwExampleReport1(DbSet<VwExampleReport1> ReportDbSet) : Report();
public sealed record VwExampleReport2(DbSet<VwExampleReport2> ReportDbSet) : Report();
public interface IReportRepository
DataTable GetReport(string reportName);
public class ReportRepository() : IReportRepository
private readonly string encodingType = "iso-8859-1";
public DataTable GetReport(string reportName)
var dbOptions = new DbContextOptionsBuilder<ReportContext>()
.UseInMemoryDatabase("BloggingControllerTest")
.ConfigureWarnings(b => b.Ignore(InMemoryEventId.TransactionIgnoredWarning))
using ReportContext db = new(dbOptions);
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
db.VwExampleReport1.Add(new VwExampleReport1 { VwExampleReport1Id = 1 });
db.VwExampleReport2.Add(new VwExampleReport2 { VwExampleReport2Id = 1 });
OneOf<VwExampleReport1[], VwExampleReport2[]> getReportResult = GetReportData(reportName, db);
return getReportResult.Match
vwExampleReport1 => vwExampleReport1.ToDataTable(),
vwExampleReport2 => vwExampleReport2.ToDataTable()
Console.WriteLine("{0}", ex.Message);
private OneOf<VwExampleReport1[], VwExampleReport2[]> GetReportData(string reportName, ReportContext db) => reportName switch
"VwExampleReport1" => db.VwExampleReport1.ToArrayAsync().Result,
"VwExampleReport2" => db.VwExampleReport2.ToArrayAsync().Result
public static class DataTableConverter
public static DataTable ToDataTable<T>(this ICollection<T> data)
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;