WCF Data Contract - best/cleanest way to enforce required values?
Asked Answered
P

1

5

I have a WCF data contract with a bunch of properties of primitive types like int and decimal, and DateTime (which is, of course, a struct).

My co-worker suggested making them all nullable and then validating required values on the service end by checking for null. I believe part of the reasoning is that since it is a serializable object, you can't enforce required values with a constructor on the data contract - and it avoids the headache of testing for default values.

However, I would also like required properties to be implicit in the contract so a client can have some idea what properties are required.

So instead of doing something like,

[DataMember] 
public Nullable<int> AgencyID { get; set; }

which would allow me to cleanly test for null on the service end, I'd do this:

[DataMember(IsRequired = true, EmitDefaultValue = true)] 
public int AgencyID { get; set; }

It is my understanding that this will throw an exception if the property hasn't been assigned a value or has a default value of 0 - which is the desired behavior. Is this the best practice for enforcing required properties on the client side? Is there any advantage to just making everything nullable and checking it on the service end instead?

Paphlagonia answered 6/12, 2012 at 17:7 Comment(2)
I am not sure I have gained 100% understanding of your question... can you please share what is your core objective here?Caldarium
Okay, I edited the question to try to clarify.Paphlagonia
C
7

I don't think its a good approach to make all of them Nullable because then client won't know by your contract that if a field is really required or not.

If you apply IsRequired=true then it's mandatory to provide field value else it would throw exception but this approach is relatively better than Nullable one...

In many scenarios I have used DTOs (Data Transfer Objects) for different services... having required fields...

Caldarium answered 6/12, 2012 at 17:31 Comment(2)
Could you provide a link for DTOs in the context that you use them?Paphlagonia
These articles may help you out... designpatternsfor.net/default.aspx?pid=99 and msdn.microsoft.com/en-us/magazine/ee236638.aspxCaldarium

© 2022 - 2024 — McMap. All rights reserved.