Reputation: 1
I have two objects:-
LabTest
LabTestDetails
Where a LabTest
object can have zero or many LabTestDetails
objects.
I need to implement the following business rule:-
The user should not be able to edit a LabTest object if it has been assigned to one or more LabTestDetails objects.
Currently i have implemented a helper method named IsAlreadyAssigned
on the LabTest object (to check if the LabTest object has been assigned to any LabTestDetails object):-
public partial class LabTest
{
public bool IsAlreadyAssigned(int id)
{
return (LabTestDetailss.Any(r2 => r2.LabTestID == id));
}}
Then i have added the following checks on the Get & Post
Edit action methods:-
public ActionResult Edit(int id)
{
LabTest c = repository.GetLabTest (id);
if ((c == null) || (c.IsAlreadyAssigned (id)))
{
return View("Error");
}
return View(c);
}
[HttpPost]
public ActionResult Edit(int id, FormCollection colletion)
{
LabTest c = repository.GetLabTest (id);
if ((c == null) || (c.IsAlreadyAssigned (id))) // *******
{
return View("Error");
}
try
{
if (TryUpdateModel(c))
{
elearningrepository.Save();
return RedirectToAction("Details", new { id = c.LabTestID });
}
}
The above might work fine on most of the cases, but if the LabTest
object were just assigned to a labTestDetails object by another user after the if ((c == null) || (c.IsAlreadyAssigned (id)))
check on the post action method i mark it as(*) on the above code , then my business logic will be broken.
so is there a way to implement my action methods so that it will always prevent editing a LabTest object if it has been assigned to a LabTestdetail object .
BR
Upvotes: 0
Views: 82
Reputation: 109185
You could use a stored procedure, as suggested in the comments, but you could also create a service method that checks whether or not a LabTest
is assigned, like
public bool LabTestIsAssigned(int labTestId)
{
using (var context = new YourContext())
{
return context.LabTestDetails.Any(d => d.LabTestID == id);
}
}
The advantage of using this method, rather than the navigation property, is that it is guaranteed to reflect the current state of the database.
Note that you'll have to do this check just before saving changes as well! Even then, an insert may occur right after evaluating the check and just before saving the changes.
Upvotes: 1