Datacontract exception. Cannot be serialized

前端 未结 6 875
天命终不由人
天命终不由人 2021-01-01 08:28

I have the following WCF DataContract:

[DataContract]
public class Occupant
{
    private string _Name;
    private string _Email;
    private string _Organi         


        
相关标签:
6条回答
  • 2021-01-01 08:55

    Try adding an empty constructor. Often times that will set off the serializer.

    0 讨论(0)
  • 2021-01-01 09:05

    Because you have provided one or more initializing constructors, you will also need to add a parameterless (default) constructor.

    i.e. You need to add:

    [DataContract]
    public class Occupant
    {
        // *** Needed only for Serialization
        public Occupant() {}
        ...
    

    This is because the default constructor disappears when you add an explicit constructor.

    [The issue isn't with the method returning List<Occupant>, since methods aren't serialized).]

    0 讨论(0)
  • 2021-01-01 09:05

    You need a default parameterless constructor. I don't ever plan to actually use mine, so I added a summary for IntelliSense and throw a run-time exception to keep it from being used.

    /// <summary>
    /// parameterless default constructor only for serialization
    /// </summary>
    public MyClass() { throw new NotImplementedException("parameterless default constructor only for serialization"); }
    
    0 讨论(0)
  • 2021-01-01 09:07

    My guess would be because _Email is not initialized. You could set EmitDefaultValue to false and see if that helps:

    [DataMember(EmitDefaultValue = false)]
    public string Email
    {
    
    0 讨论(0)
  • 2021-01-01 09:10

    When you have NO setter by default, do these steps:

    1. Add parametreless constructor;
    2. And add private set at least.

    This helps me.

    0 讨论(0)
  • 2021-01-01 09:12

    You should add an empty parameter constructor to your datacontract class

    0 讨论(0)
提交回复
热议问题