1

I'm trying to serialize an object to xml using XmlSerializer but keep getting this error:

System.InvalidOperationException: [MySql.Data.MySqlClient.MySqlParameter] cannot be serialized because it does not have a parameterless constructor.

I followed the solution to why xml serializable class need a parameterless constructor which seems to have solved the problem for everyone else, but I still get an error. When I add public MyClass() it gives me 'MyClass.MyClass()' must declare a body because it is not marked abstract, extern, or partial, so I add a body and the first error comes back.

Note that originally there aren't any constructors, parameterless or otherwise, so I don't understand why it isn't just automatically creating its own.

What am I doing wrong?

Code added:

MyFile.cs

public async Task Save(MyClass xmlObj)
{
    XmlSerializer xmlSer = new XmlSerializer(this.GetType()); //I think the problem is likely to be here
    StringWriter strWriter = new StringWriter();

    xmlSer.Serialize(strWriter, xmlObj);
    objToUpdate.ColName = (strWriter.ToString());
    await dbContext.SaveChangesAsync();
}

File.cs

public async Task<IActionResult> SaveData(params...)
{
    await new MyFile<MySqlParameter>(accessParam, dbContext).Save(xmlObj);
}
half of a glazier
  • 1,864
  • 2
  • 15
  • 45
  • The issue is surely that `MySqlParameter` can't be serialised, not `MyClass` - so why are you adding a constructor to `MyClass`? And what version of `MySql` are you using? Because [`MySqlParameter` *does* have a parameterless constructor](https://dev.mysql.com/doc/dev/connector-net/8.0/html/M_MySql_Data_MySqlClient_MySqlParameter__ctor.htm). Can you post a compilable reproduction of your problem? – Matthew Watson Feb 20 '20 at 08:45
  • Why would it be trying to serialise `MySqlParameter`? That's only the data being sent to the db when saving, it's in the parent method, not with the `XmlSerializer` – half of a glazier Feb 20 '20 at 09:13
  • are you tried to change your constructor to ``private`` or ``internal``? – Mohammed Sajid Feb 20 '20 at 09:26
  • Yes, tried all three – half of a glazier Feb 20 '20 at 09:28
  • `Why would it be trying to serialise` - I don't know why, but the error message clearly states that it *is* being serialised. You will need to post some code. – Matthew Watson Feb 20 '20 at 09:29
  • Added basic code, let me know if it's missing something – half of a glazier Feb 20 '20 at 09:38

2 Answers2

1

You should have added

public MyClass(){}

to the class. There is a difference between no body and an empty body which is what you want on this constructor.

1

I figured it out...

I had been creating a new XmlSerializer and passing in a parameter as posted in a SO answer:

XmlSerializer xmlSer = new XmlSerializer(this.GetType());

When really it works perfectly fine to use the same XmlSerializer as the deserialization:

XmlSerializer objSer = new XmlSerializer(typeof(MyClass));

half of a glazier
  • 1,864
  • 2
  • 15
  • 45