0

Supposing that we have the following code for WCF service and a database with an Employee table.

Why use [DataContract] and what are benefits of using all [DataMember] ? We can use all Employee details without using [DataContract].

[ServiceContract]
public interface IEmployeeService
{
    [OperationContract]
    Employee GetEmployeeDetails(int EmpId);
}

[DataContract]
public class Employee
{
    private string m_Name;
    private int m_Age;
    private int m_Salary;

    [DataMember]
    public string Name
    {
        get { return m_Name; }
        set { m_Name = value; }
    }

    [DataMember]
    public int Age
    {
        get { return m_Age; }
        set { m_Age = value; }
    }

    [DataMember]
    public int Salary
    {
        get { return m_Salary; }
        set { m_Salary = value; }
    }

}

Implementatin of Service:

public class EmployeeService : IEmployeeService
{
    public Employee GetEmployeeDetails(int empId)
    {

        Employee empDetail = new Employee();
        return empDetail;
    }
}

And our Client:

private void btnGetDetails_Click(object sender, EventArgs e)
    {
        EmployeeServiceClient objEmployeeClient = new EmployeeServiceClient();
        Employee empDetails;
        empDetails = objEmployeeClient.GetEmployeeDetails(empId);
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
BMA
  • 33
  • 6
  • 1
    Have you heard about Serialization and Deserialization? There is enough material available on MSDN or internet regarding this. In short these attributes helps to translates between .NET Framework objects and request/response payloads (formats like XML, JSON) in both directions. – Pankaj Kapare Feb 21 '16 at 12:14
  • 1
    If you don't use any `[DataMember]` attributes, then **all** public properties will be included in your data contract. If that's what you want - fine. But you might have cases where you **don't want** to include *all* public properties into your data contract - then you need to mark those that you do want with `[DataMember]` attributes, and all others without this attribute will be ignored – marc_s Feb 21 '16 at 14:38
  • Thanks, more clearly now. – BMA Feb 22 '16 at 06:35

0 Answers0