I've a Table SiteReport
which can have Many Asset
, And each Asset can only have one Certificate
. So its One-to-Many & then One-to-One relationship. As shown below.
I'm trying to delete a SiteReport in the given method, So that all Assets under the Report and all associated Certificates will be deleted.
public ActionResult DeleteSiteReport(long siteReportId)
{
SiteReport report;
List<Asset> reportAssets;
using (var ctx = new ApplicationDbContext())
{
report = ctx.SiteReport.Include(i => i.Assets).SingleOrDefault(x => x.site_report_id == siteReportId);
reportAssets = ctx.Asset.Include(i => i.Certificate).Where(x => x.site_report_id == siteReportId).ToList<Asset>();
foreach (Asset asset in reportAssets)
{
Certificate cert = ctx.Certificate.SingleOrDefault(x => x.report_asset_id == asset.report_asset_id);
ctx.Certificate.Remove(cert);
ctx.Asset.Remove(asset);
}
ctx.SiteReport.Remove(report);
ctx.SaveChanges();
}
return RedirectToAction("ViewReports");
}
Is this a correct/best way of doing it ? How to failproof it?