When using the DataContract serializer, it fails to deserialize the Id
value as in the below sample:
using System;
using System.Runtime.Serialization;
using System.Xml.Linq;
public class Program
{
private const string SAMPLE_VALIDATION_RESULT_XML = @" <ValidationResult>
<Message>The FooBar record has duplicate key values.</Message>
<Id>Microsoft.LightSwitch.EntityObject.DuplicateKey</Id>
<Target>http://localhost:55815/ApplicationData.svc/FooBar(0)</Target>
</ValidationResult>";
[DataContract(Name = "ValidationResult", Namespace = "")]
public class ValidationResult
{
[DataMember]
public string Message { get; set; }
[DataMember]
public string Id { get; set; }
[DataMember]
public string Target { get; set; }
}
public static void Main()
{
var doc = XDocument.Parse(SAMPLE_VALIDATION_RESULT_XML);
using (var reader = doc.CreateReader())
{
reader.MoveToContent();
var res = (new DataContractSerializer(typeof(ValidationResult))).ReadObject(reader) as ValidationResult;
Console.WriteLine($"res.Id = \"{res.Id}\", expected \"Microsoft.LightSwitch.EntityObject.DuplicateKey\"");
}
}
}
I'm guessing it's to do with the referential integrity features, but I only found one option to disable that (on the DataContractSerializer), and it didn't affect the outcome.
I can't change the name of the Id
field, as it's a third-party API, so how can I access that value?
Specify order of members
[DataContract(Name = "ValidationResult", Namespace = "")]
public class ValidationResult
{
[DataMember(Order = 0)]
public string Message { get; set; }
[DataMember(Order = 1)]
public string Id { get; set; }
[DataMember(Order = 2)]
public string Target { get; set; }
}
Without specifying an order, the DataContractSerializer
expects the members will be in alphabetical order. See Basic rules. It is obvious that the order established by the service provider. So you must specify it.