Sometimes data is deleted from a database by a user which has been referred to. A try catch in razor will handle this just fine, but is there another way?
Current Situation: The model holds a list of Boxes. Each Box has a Container. Safeguarding against Container deletion to avoid errors means using try catch.
No error handling,
<td>@m.Container.Name</td>
Error handling,
<td>@try{@m.Container.Name}catch { Deleted }</td>
Many lists have similar situations, where it is possible that relational data may be removed. Is there a better way to accomplish this aside from this try catch approach?
Some extra code to help with the example:
View Model:
public class BoxVM
{
List<Box> Boxes { get; set; }
}
Models:
public class Box
{
public int BoxId { get; set; }
public Material Material { get; set; }
public Container Container { get; set; }
}
public class Material
{
//fk
public int BoxId { get; set; }
public string Description { get; set; }
}
public class Container
{
//fk
public int BoxId { get; set; }
public string Name { get; set; }
}
Controller:
public ActionResult showBoxList()
{
var vm = new BoxVM();
vm.boxes = _boxRepo.Get().ToList();
var materials = _materialRepo.Get().ToList();
var containers = _containerRepo.Get().ToList();
foreach(var box in vm.boxes)
{
box.Material = materials.Where(m => m.BoxId == box.BoxId).Single();
box.Container = containers.Where(c => c.BoxId == box.BoxId).Single();
}
return View(vm);
}
View:
@model BoxVM
foreach(var m in Model.boxes)
{
<p>@m.Container.Name</p> @*// Breaks if specific container was deleted *@
<p>@try{@m.Container.Name}catch{<text>Deleted</text>}</p> @*// Doesn't break, but is there a better way? *@
}
Is there a better way to accomplish this aside from this try catch approach?
Yes. Use an approach which supports a verbose referential integrity policy allowing for the deletion of a single node in an object graph while maintaining the relevance of the object graph.