IgnoreDataMember attribute in WCF POCO Serialization

POCO stands for PLAIN OLD CLR OBJECT.

If  in WCF we are using

1. Complex Data type for example custom class

2. And not attributing this custom class as DataContract and properties of the class as DataMember

3. If we want to expose the below custom class to client and not using DataContractSeraliazer then all public properties will be automatically serialized

public class MyCustomData
{
    public string Name { get; set; }
    public string RollNumber { get; set; }
    public string Subject { get; set; }
}

Automatically POCO (Plain old CLR Object) is serialized without using DataContract attribute. So to test this, let us create service contract

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        MyCustomData GetData();
    }

And service implementation is as below


    public class Service1 : IService1
    {
        public MyCustomData GetData()
        {
            MyCustomData data = new MyCustomData { Name = "John", RollNumber = "1", Subject = "WCF" };
            return data;
        }
    }

So when we consume this service at client side

clip_image002

We can use that as above

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsoleApplication1.ServiceReference1;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Service1Client proxy = new Service1Client();
            MyCustomData data = proxy.GetData();
            Console.WriteLine(data.Name + data.Subject + data.RollNumber);
            Console.ReadKey(true);
        }
    }
}

Now we know how we could serialize custom data or class without using DataContractSerlializer. But if we notice all the public property are serialized. If we want to hide some of public property from serialization then we will use IgnoreDataMember

 public class MyCustomData
    {

        public string Name { get; set; }
        [IgnoreDataMember]
        public string RollNumber { get; set; }
        public string Subject { get; set; }
    }

Add the namespace System.RunTime.Serilization to work with IgnoreDataMember attribute.

Now we are hiding public property RollNumber with IgnoreDataMember attribute , so at the client side when we try to access RollNumber property on custom class MyCustomData we will get the below compile time error.

clip_image004[5]

Error says there is no definition for RollNumber is present at the client side.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com