KnownType attribute in wcf: Part 6

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

According to msdn the KnownTypeAttribute class allows you to specify, in advance, the types that should be included for consideration during deserialization. The wcf service generally accept and returns the base type. If you expect the service to accept and return inherited type then we use knowntype attribute. In other words by default you cannot use subclass of data contract class instead of its base class. We need to tell explicitly to wcf about the subclass using the knowntype attribute. Let me explain by using example.

Create a wcf application and implement the following datacontract.

using System.Runtime.Serialization;
using System.ServiceModel;

namespace WcfDemo
{
[ServiceContract]
public interface IBuilder
{
[OperationContract]
Builder GetBuilder();
}

[DataContract]
public class Builder
{
public int BuilderId {get; set;}
public int BuilderName {get; set;}
public int MobileNo {get; set;}
public enum BuilderType { DayBasic=1, ContractBasis=2}
}

public class DayBasic: Builder
{
public int LabourCharges {get; set;}
public int WorkedDay {get; set;}

}

public class ContractBasis: Builder
{
public int TotalAmount {get; set;}
public int DayComplited {get; set;}
}
}
As above said that we can not use subclass of data contract class instead of its base class. To achive that i am going to use KnownTypeAttribute.

using System.Runtime.Serialization;
using System.ServiceModel;
namespace WcfDemo { [ServiceContract] public interface IBuilder { [OperationContract] Builder GetBuilder(); } [KnownType(typeof(DayBasic))] [KnownType(typeof(ContractBasis))] [DataContract] public class Builder { public int BuilderId {get; set;} public int BuilderName {get; set;} public int MobileNo {get; set;} public enum BuilderType { DayBasic=1, ContractBasis=2} } public class DayBasic: Builder { public int LabourCharges {get; set;} public int WorkedDay {get; set;} } public class ContractBasis: Builder { public int TotalAmount {get; set;} public int DayComplited {get; set;} } }

Happy coding :)

Tags: , , , ,

  • niraj

    what is [KnownType(typeof(DayBasic))][KnownType(typeof(ContractBasis))]

    • Pramod Kumar

      Hi Niraj, Please read the article carefully.. You will get understood..