DataContractSerializer - DBNull.Value

时间:2017-04-24 06:25:39

标签: c# wcf serialization null dbnull

从我的WCF客户端,我调用一个方法来服务。作为参数,我传递一个位数组,这是我的自定义类的序列化对象:

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;
    }
}

问题是列表Parameters中的数组可以包含DBNull.Value,默认情况下DataContractSerializer不支持。如果我将DBNull添加到支持的类型,代码会减慢很多,所以我无法通过这种方式解决它。我怎样才能使它发挥作用?

1 个答案:

答案 0 :(得分:1)

我不确定这是你想要的,但它可能有所帮助。使用此方法,您可以检查DataSet是否为空值并替换它们:

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;
        }