当保存包含所有更改的集合时,我如何确保空字符串被保存为NULL?我正在使用linq、wpf和wcf。
我不想为每个记录和每个属性迭代以在为空时放置null。
当保存包含所有更改的集合时,我如何确保空字符串被保存为NULL?我正在使用linq、wpf和wcf。
我不想为每个记录和每个属性迭代以在为空时放置null。
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>
[DataContract]
class MyDataStructure
{
[DataMember]
string Foo { get; set; }
[OnSerializing]
void OnSerializing(StreamingContext context)
{
if (Foo == String.Empty)
Foo = null;
}
}
如果您有很多字符串属性并且不想编写测试每个属性的代码,您可以始终使用反射通过类的属性进行循环。