Need to throw my own exception RRS feed

  • Question

  • I have two entity classes, WorkOrder and EmployeeWorkOrder.  EmployeeWorkOrder objects cannot exist without WorkOrder objects, so they're tied together and enforced by an FK constraint.

    That works fine, and LINQ is technically doing what I intend to do, but not quite.  Currently, attempting to insert an EmployeWorkOrder with a null WorkOrder throws the InvalidOperationException "An attempt was made to remove a relationship between a WorkOrder and an EmployeeWorkOrder....".

    That exception is not nearly as useful to myself and fellow developers as the custom exception I intend to throw, but I cannot for the life of me get my exception thrown.  I would expect to be able to catch it at OnValidate, but I've tried that and my code is not being called before the InvalidOperationException gets thrown by LINQ.  I've also tried implementing InsertEmployeeWorkOrder and trapping it there, but still no joy, InvalidOperationException.  Any ideas?  It almost seems like LINQ has its own extra validation steps that I can't find any info on.

    Thursday, July 31, 2008 5:31 PM

All replies

  • Can you please verify the OnValidate() method you implemented (again)?


    I wrote a simple (WorkOrder and EmployeeWorkOrder) application like you describe, and implemented the OnValidate() method -- and I can see that the method is invoked before the exception is thrown.


    Am I missing something?






    Friday, August 1, 2008 9:18 PM
  • Sure, it's:


    Code Snippet

    partial void OnValidate(ChangeAction action)

        switch (action)
            case ChangeAction.Update:
            case ChangeAction.Insert:
                if (WorkOrder == null)

                    // truncated exception message:

                    throw new DomainLogicException("Cannot save an EmployeeWorkOrder...");



    This is the same method I use to validate the presense of a value for required value types (string, decimal, etc.), but it does not seem to work for entity references.  I have a test assertion method (MyAssert.Throws(Action, Type, Message)) that checks for an exception of a specific type to be thrown, and it only ever catches an InvalidOperationException on these.


    Also worth noting that checking for WorkOrderID to be greater than one in OnValidate() doesn't work in the cases where a newly instantiated WorkOrder object was marked InsertOnSubmit() along with its EmployeeWorkOrder objects, because the WorkOrder doesn't have an ID yet, but the WorkOrder property is not null.


    Thanks for the reply,


    Saturday, August 2, 2008 12:22 PM