简体   繁体   English

DataContractSerializer-DBNull.Value

[英]DataContractSerializer - DBNull.Value

From my WCF client I call a method to the service. 从WCF客户端,我调用服务的方法。 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. 问题是参数列表中的数组可以包含DBNull.Value,默认情况下DataContractSerializer不支持。 If I add DBNull to the supported types, the code slows down a lot, so I can't solve it this way. 如果我将DBNull添加到受支持的类型,则代码会减慢很多速度,因此无法以这种方式解决。 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: 使用此方法,您可以检查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;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM