InvalidOperationException when serializing SqlParameter after moving from .NET 1.1 to 2.0

Today, I had an strange exception
‘System.InvalidOperationException’ occurred in System.Xml.dll on a code, what was working without troubles in old Framework 1.1:

SqlParameter[] cmdParams = new SqlParameter[1];
cmdParams[0] = new SqlParameter("@result", SqlDbType.Int, 0, ParameterDirection.ReturnValue, false, 0, 0, "", DataRowVersion.Current, 0);

StringWriter sw = new StringWriter();
XmlSerializer xser = new XmlSerializer(cmdParams.GetType());
xser.Serialize(sw, cmdParams); // <- Exception

The exception message was:
{"The type System.Data.SqlTypes.SqlInt32 may not be used in this context. To use System.Data.SqlTypes.SqlInt32 as a parameter, return type, or member of a class or struct, the parameter, return type, or member must be declared as type System.Data.SqlTypes.SqlInt32 (it cannot be object). Objects of type System.Data.SqlTypes.SqlInt32 may not be used in un-typed collections, such as ArrayLists."}

After simulating the problem in a different small project, I have discovered, that problem is caused by setting value parameter (last one in SqlParameter constructor I am using).
While, this is ReturnValue parameter, i can easy change the value (of type object) to null, and with this small change, everything works correctly and XmlSerialization is done properly.

Corrected code:

SqlParameter[] cmdParams = new SqlParameter[1];
cmdParams[0] = new SqlParameter("@result", SqlDbType.Int, 0, ParameterDirection.ReturnValue, false, 0, 0, "", DataRowVersion.Current, null);

StringWriter sw = new StringWriter();
XmlSerializer xser = new XmlSerializer(cmdParams.GetType());
xser.Serialize(sw, cmdParams);

 
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s