What a DataContract and DataMember are in WCF: Part 5

Before reading this article, I highly recommend reading my previous parts:

DataContact
A datacontract is formal agreement between a client and service that abstractly describe 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

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 int StudentName
{
get { return Name; } set { Name = value; }
}

[DataMember]
public int MobileNo
{
get { return Mobile; } set { Mobile = value; }
}
}
}

In Service1.svc.cs


namespace WcfDemo
{
public class Service1 : IStudent
{
public  Student GetStudent()
{
Student objStudent = new Student();
objStudent.StudentId = 1;
objStudent.StudentName = "Pramod";
objStudent.MobileNo = "9876543210";
return objStudent;
}
}
}
Properties of DataMember:EmitDefaultValue: We can set default value in .net framework. We can set default value in datamember. We can achieve this by using 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 is 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 while schema generated. By default it is what we declare in our datamember. In code i have written datamember as following

[DataMember(Name="RegistrationNo")]
public int StudentId
{
get { return Id; } set { Id = value; }
}

But now i want to show RegistrationNo instead of StudentId in xml. In that case we use Name property.

Order: By using this property We can set datamemeber order. It means we set which datamember shows first or which shows last.

[DataMember(Order=1)]
public int StudentId
{
get { return Id; } set { Id = value; }
}

Tags: , , ,

  • niraj

    Really nice articles!
    Looking forward to your new lessons in WCF!