I'm working on a reporting feature that outputs to HTML tables in Razor pages. The reports have a lot of similar fields (i.e. FirstName) and I'd like to apply the DRY Principal as much as possible while keeping the code simple. On the database side the reports are generated using stored procedures. On the .NET side, I was planning to use EF but not sure if there's a better way. Using EF, I find myself repeating a lot of code.
For example say I have:
Report1Model.cs which has properties FirstName and Report1Field
Report2Model.cs which has properties FirstName and Report2Field
Then in my page model I have:
public List<Report1> Report1Result { get; set; }
public List<Report2> Report2Result { get; set; }
...
if (Report == "Report1")
Report1Result = _db.Report1.FromSqlRaw<Report1>($"exec spReport1").ToList();
else if (Report == "Report2")
Report2Result = _db.Report2.FromSqlRaw<Report2>($"exec spReport2").ToList();and finally in my razor page I have:
@if (Model.Report == "Report1")
{
@if (Model.Report1Result != null && ModelState.IsValid)
{
if (Model.Report1Result.Count == 0)
{
<div>No Records Found</div>
}
else
{<table id="dataTable" class="display"><thead><tr><th>First Name</th><th>Report 1 Field</th></tr></thead><tbody>
@foreach (var result in Model.Report1Result)
{<tr><td>@result.FirstName</td><td>@result.Report1Field</td></tr>
}</tbody></table>
}
}
}
@if (Model.Report == "Report2")
{
@if (Model.Report2Result != null && ModelState.IsValid)
{
if (Model.Report2Result.Count == 0)
{
<div>No Records Found</div>
}
else
{<table id="dataTable" class="display"><thead><tr><th>First Name</th><th>Report 2 Field</th></tr></thead><tbody>
@foreach (var result in Model.Report2Result)
{<tr><td>@result.FirstName</td><td>@result.Report2Field</td></tr>
}</tbody></table>
}
}
}So instead of repeating so much, is there a good way to call different stored procedures (that will return different fields) and dynamically / programmatically loop through those fields? Thanks in advance for any tips.