views:

1182

answers:

1

OK here's my problem...

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 to see 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 to see 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. I only want those count checks 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.

Sorry, I know it sounds confusing....

A: 

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.

public IEnumerable<RuleViolation> GetRuleViolations( ChangeAction action )
{
    if (action == ChangeAction.Delete) {
       ...
    }
    else {
       ...
    }
}

public IEnumerable<RuleViolation> GetRuleViolations()
{
    return GetRuleViolations( ChangeAction.None );
}
tvanfosson
Ah, perfect! Thanks very much!