I have a LINQ partial class:
public partial class resp { public IEnumerable<RuleViolation> GetRuleViolations() { if (String.IsNullOrEmpty(respName)) yield return new RuleViolation('Responsibility name required', 'respName'); yield break; } public bool IsValid { // Quick method for checking to see whether an object contains any RuleViolations get { return (GetRuleViolations().Count() == 0); } } partial void OnValidate(ChangeAction action) { // Hook to LINQ to be notified before db is actually persisted .. and check to make sure resp is not used by respApprover or approvals if (action == ChangeAction.Delete && ((respApprovers.Count() != 0 || approvals.Count() != 0))) throw new ApplicationException('You cannot delete a responsibility that is in use'); if (!IsValid) throw new ApplicationException('Rule violations prevent saving'); } }
In my code I would like to be able to check whether a responsibility (dbo.resp) exists before it is deleted.
I am accomplishing this check with a hook to OnValidate as above ... if (action == ChangeAction.Delete) ... and returning an application exception if it fails.
Also, during normal validation, I would like to check to make sure rule violations aren’t made (resp.respName in this case…)
So, normally I can just do a try { } catch { var errors = resps.GetRuleViolations() } and check whether I have validation errors. Of course, that doesn’t know what action is being taken (Changeaction.Delete)
I guess my main question is, how can I have OnValidate return a reason rather than crash my whole app when the Changeaction is delete. Normally I would catch GetRuleViolations but if I put the ‘if statement’ in the GetRuleViolations … it will always be true even during checks to see if the data was correct (in other words, respApprovers.Count() will matter even for checks on new insertions which I don’t want to. I only want those count checks to be made on deletion)
Or possibly more simply stated: I want GetRuleViolations to tell me when someone attempts to delete resp that has respApprovers.Count() > 0 or approvals.Count() > 0 but only when the OnValidate Changeaction is delete.
Change GetRuleViolations to accept the ChangeAction parameter and add a parameterless version that calls it with ChangeAction.None (or Update or Insert, as appropriate). Then move your check in there as you want.