Storing NULL instead of empty row columns

Keeping a collection with all the changes, how can I guarantee that empty lines should go as NULL? I am using linq, wpf, wcf.

I do not want to iterate over each record and each property of the record to put a zero if empty.

+3
source share
2 answers

You can implement the [OnSerializing] event in your WCF DataContract to check String.Empty and change it to null. EG:

[DataContract]
class MyDataStructure
{
    [DataMember]
    string Foo { get; set; }

    [OnSerializing]
    void OnSerializing(StreamingContext context)
    {
        if (Foo == String.Empty)
            Foo = null;
    }
}

And if you have many string properties and you do not want to write code to check each of them, you can always use Reflection to scroll through the properties of the class.

+1
source

IValueConverter, : ,

public class DoubleNullFromStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is double || value is double?) return value;
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return null;

        var strValue = value as string;
        if (strValue == null || strValue.Trim().Length == 0)
            return null; //allow empty strings and whitespaces

        double doubleValue = 0;
        if (double.TryParse(strValue, out doubleValue))
            return doubleValue;

        return value; //which will intenionally throw an error 
    }
}

, .

<TextBox HorizontalAlignment="Left" Name="brokeragePaidText" VerticalAlignment="Top" Width="170" >
        <TextBox.Text>
            <Binding Source="{StaticResource insertTransaction}" Converter="{StaticResource DoubleNullFromStringConverter}" UpdateSourceTrigger="Explicit" Path="BrokeragePaid">
                <Binding.ValidationRules>
                    <ExceptionValidationRule/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
+2

Source: https://habr.com/ru/post/1787742/


All Articles