Reputation: 379
My team is developing a WCF service to communicate with database tables. Lately, we have been noticing that if we insert a new record to some of the tables, the integer and Boolean values would not be saved to the record, but strings would work just fine.
It appeared that functions in the service that receive a DataContract class as a parameter would have null values for all their non-string properties.
I have set up a new class to test this out:
[DataContract]
public class MyObject
{
private string _Name;
[DataMember]
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private int? _TestInt;
[DataMember]
public int? TestInt
{
get { return _TestInt; }
set { _TestInt = value; }
}
public MyObject()
{
_Name = "";
_TestInt = 0;
}
}
I have added functions to my service to simply return the value of the properties in the above class:
[OperationBehavior]
public string GetMyName(MyObject myObject)
{
return myObject.Name;
}
[OperationBehavior]
public int? GetMyTestInt(MyObject myObject)
{
return myObject.TestInt;
}
I have configured the service reference on my client application to not reuse types in referenced assemblies.
This is the code I use to test on the client:
MyObject record = new MyObject();
record.Name = "This is Me";
record.TestInt = 5;
int? returnValue = _client.GetMyTestInt(record);
string message;
if (returnValue == null)
message = "Integer value is null.";
else
message = "Integer value is " + returnValue.ToString();
MessageBox.Show(message, _client.GetMyName(record));
The code above shows a message that the integer returned by my service is null, instead of the 5 that I assigned it. GetMyName, however, does return the proper value for my string, which displays as the caption of my message box.
Why is it that the service seems to be receiving null values?
Upvotes: 2
Views: 6554
Reputation: 11
In DataContract Add the Property attribute as
[DataMember(IsRequired = true)]
Upvotes: 1
Reputation: 5322
You have to add the [DataMember] attribute to the backing field.
Change your contract like this:
[DataContract]
public class MyObject
{
[DataMember] // data contract on backing field
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
[DataMember] // data contract on backing field
private int? _TestInt;
public int? TestInt
{
get { return _TestInt; }
set { _TestInt = value; }
}
public MyObject()
{
_Name = "";
_TestInt = 0;
}
}
Upvotes: 2