简体   繁体   中英

WCF Service Receiving Null Values from DataContract

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?

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;
    }
}

In DataContract Add the Property attribute as

[DataMember(IsRequired = true)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM