Before reading this article, I highly recommend reading my previous parts:
- Introduction to WCF: Part 1
- Introduction to Endpoint in WCF: Part 2
- How to Make Changes to WCF Service Without Breaking Client in WCF: Part 3
- Method Overloading in WCF: Part 4
DataContact
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.
Creating a basic DataContract and DataMember
- using System.Runtime.Serialization;
- using System.ServiceModel;
- namespace WcfDemo
- {
- [ServiceContract]
- public interface IStudent
- {
- [OperationContract]
- Student GetStudent();
- }
- [DataContract]
- public class Student
- {
- int Id = 0;
- string Name = "";
- string Mobile = "";
- [DataMember]
- public int StudentId
- {
- get { return Id; }
- set { Id= value; }
- }
- [DataMember]
- public string StudentName
- {
- get { return Name; }
- set { Name = value; }
- }
- [DataMember]
- public string MobileNo
- {
- get { return Mobile ; }
- set { Mobile = value; }
- }
- }
- }
- namespace WcfDemo
- {
- public class Service1 : IStudent
- {
- public Student GetStudent()
- {
- Student objStudent = new Student();
- objStudent.StudentId = 1;
- objStudent.StudentName = "Pramod";
- objStudent.MobileNo = "9876543210";
- return objStudent;
- }
- }
- }
- EmitDefaultValue: We can set a default value in the .Net Framework. We can set the default value in the datamember. We can do this using the EmitDefaultValue property. By default it is false.
- [DataMember(EmitDefaultValue=false)]
- public int StudentId
- {
- get { return Id; } set { Id = value; }
- }
- IsRequired: By using this property we can set the datamemeber as mandatory. By default it is false.
- [DataMember(IsRequired=true)]
- public int StudentId
- {
- get { return Id; } set { Id = value; }
- }
- Name: By using this property we can set a datamember name when the schema is generated. By default, it is what we declare in our datamember. In code I have written the datamember as in the following;
But now, I want to show RegistrationNo instead of StudentId in XML. In that case we use the Name property.- [DataMember(Name=“RegistrationNo”)]
- public int StudentId
- {
- get { return Id; } set { Id = value; }
- }
- Order: By using this property we can set the datamemeber order. In other words, we set which datamember shows first or which shows last.
- [DataMember(Order=1)]
- public int StudentId
- {
- get { return Id; } set { Id = value; }
- }

Duncan BorgPosted Sep 2, 2020, 4:22 AM
By Default emitDefaultValue is true not false
Mohan KrishnaPosted Mar 4, 2017, 12:34 AM
Can you post the part 4 article. When I click on part 4 link, it is redirecting to home page