Search code examples
wcfvalidationentity-framework-4wcf-client

Approach to pass validation result, on failure, from WCF service (with EF4 data processing) to MVC3 client


I implement a ASP.NET MVC3 application, where data is accessed through WCF services. The WCF service uses EF4.1 for data access with DBContext and POCO classes for entities. I can annotate the properties with data validations attributes on the server side, and also I can implement custom validation by defining either custom validation attributes (derived from ValidationAttribute), or by implementing IValidatableObject ).

But I have a problem: if validation fails, what is the best approaoch to pass validation error info from WCF to client, and then use it in MCV3 client?

As I understand with WCF, every data exchanged between client and WC service should be part of the data contract, and should not use exceptions as ways of passing meaningful information between server and client (like throwing a ValidationException with extra properties set for Validation failure info).

Also in WCF who uses EF I call dbContext.SaveData(), but if data is not valid, it throws exception, which I don't want.

So:

  1. how can I call validation explicitly in EF and make sure either the object is valid and I can call SaveData(), or the object is invalid and I can collect somehow validation failure information to pass to client.

  2. Haw can I pass this validation failure information back to client, as part of data contract, and not an an exception.

Thanks


Solution

  • You can use two approaches:

    • Use standard response data contract for success and fault contract with FaultException<YourFaultContract> for validation failure. Typed fault exceptions are way to define "expected" exceptions - it is just another data contract passed in SOAP Fault describing some failure.
    • Create response data contract which contains something like result code, response data, failure message etc. and use this data contract for both success and failure. I don't like this approach but it is easier to use in some ESB where faults are processed in special way.