简体   繁体   中英

DataContractSerializer - DBNull.Value

From my WCF client I call a method to the service. As an argument I pass an array of bits which is a serialized object of my custom class:

public class MySqlCommand
{
    public string CommandText;
    public List<object[]> Parameters;

    public MySqlCommand()
    {
        Parameters = new List<object[]>();
    }
    public static MySqlCommand GetSQLCommand(string CommandID)
    {
        MySqlCommand command = new MySqlCommand();
        command.CommandText = CommandID;
        return command;
    }
}

The problem is that the arrays in the list Parameters can contain DBNull.Value, which is not supported by the DataContractSerializer by default. If I add DBNull to the supported types, the code slows down a lot, so I can't solve it this way. How can I make it work?

I'm not sure this is what you want but it might help. with this method you can check a DataSet for null values and replace them:

public static DataSet DBNull(DataSet dataSet)
    {
        try
        {
            foreach (DataTable dataTable in dataSet.Tables)
                foreach (DataRow dataRow in dataTable.Rows)
                    foreach (DataColumn dataColumn in dataTable.Columns)
                        if (dataRow.IsNull(dataColumn))
                        {
                            if (dataColumn.DataType.IsValueType) dataRow[dataColumn] = Activator.CreateInstance(dataColumn.DataType);
                            else if (dataColumn.DataType == typeof(bool)) dataRow[dataColumn] = false;
                            else if (dataColumn.DataType == typeof(Guid)) dataRow[dataColumn] = Guid.Empty;
                            else if (dataColumn.DataType == typeof(string)) dataRow[dataColumn] = string.Empty;
                            else if (dataColumn.DataType == typeof(DateTime)) dataRow[dataColumn] = DateTime.MaxValue;
                            else if (dataColumn.DataType == typeof(int) || dataColumn.DataType == typeof(byte) || dataColumn.DataType == typeof(short) || dataColumn.DataType == typeof(long) || dataColumn.DataType == typeof(float) || dataColumn.DataType == typeof(double)) dataRow[dataColumn] = 0;
                            else dataRow[dataColumn] = null;
                        }

            return dataSet;
        }
        catch (Exception ex)
        {
            return dataSet;
        }

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