Note that there are some explanatory texts on larger screens.

plurals
  1. POPossible to avoid repetitive try catch in this scenario?
    text
    copied!<p>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?</p> <p>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.</p> <p>No error handling,</p> <pre><code>&lt;td&gt;@m.Container.Name&lt;/td&gt; </code></pre> <p>Error handling,</p> <pre><code>&lt;td&gt;@try{@m.Container.Name}catch { Deleted }&lt;/td&gt; </code></pre> <p>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?</p> <p>Some extra code to help with the example:</p> <p>View Model:</p> <pre><code>public class BoxVM { List&lt;Box&gt; Boxes { get; set; } } </code></pre> <p>Models:</p> <pre><code>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; } } </code></pre> <p>Controller:</p> <pre><code>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 =&gt; m.BoxId == box.BoxId).Single(); box.Container = containers.Where(c =&gt; c.BoxId == box.BoxId).Single(); } return View(vm); } </code></pre> <p>View:</p> <pre><code>@model BoxVM foreach(var m in Model.boxes) { &lt;p&gt;@m.Container.Name&lt;/p&gt; @*// Breaks if specific container was deleted *@ &lt;p&gt;@try{@m.Container.Name}catch{&lt;text&gt;Deleted&lt;/text&gt;}&lt;/p&gt; @*// Doesn't break, but is there a better way? *@ } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload