I need to have some data members get some values when I create an instance of the DataContract on the client. This is not happening using constructors. I have searched through different forums and found we have to use [OnDeserializing] and [OnDeserialized] attributes. This is also not working. Can somebody suggest something here. The other alternative is creating constructors in the partial classes at the client side. I want to avoid that.
Please find the code below:
Server-side: Datacontract
[DataContract]
public class Account
{
private int mAccountId;
private string mAccountName;
public Account()
{
mAccountId = 5;
mAccountName = "ABC";
}
[OnDeserializing]
public void OnDeserializing(StreamingContext context)
{
mAccountId = 5;
mAccountName = "ABC";
}
[OnDeserialized]
public void OnDeserialized(StreamingContext context)
{
}
[DataMember]
public int AccountId
{
get
{
return mAccountId;
}
set
{
mAccountId = value;
}
}
[DataMember]
public string AccountName
{
get
{
return mAccountName;
}
set
{
mAccountName = value;
}
}
}
Client side – initialization
namespace TestClient
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Account acc = new Account();
}
}
}
The code generator used to create WCF proxy classes creates compatible contract types, and doesn’t used the exact same type as used by the WCF service. The easiest way to achieve what you want, is to create the constructor yourself on your client, as the code generated is
partial:If you don’t want to do this, you can get WCF to reuse types that are already referenced by your client project. So if your data contract classes are in a separate library (as is recommended), you can reference that library and then reconfigure your WCF client project to reuse the shared types from the referenced assembly.