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?
The DataContract attribute is used to mention the custom class as data contract and the DataMember attribute is used to mention the data member as a member of the data contract.
A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.
Data Contracts can be defined as follows: It describes the external format of data ed to and from service operations. It defines the structure and types of data exchanged in service messages. It maps a CLR type to an XML Schema. It defines how data types are serialized and deserialized.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With