Storing NULL instead of blank string columns
While saving a collection with all the changes, how can i ensure that blank strings should go as NULLs? I am using linq, wpf, wcf.
I don't want to iterate for each record and each property of record to 开发者_高级运维put a null if blank.
You can use a IValueConverter class like following :: Below code is for double, you can stimulate the behavior for other types
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
}
}
Then Bind this to your control like following
<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>
You could implement the [OnSerializing] event in your WCF DataContract to check for 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 a lot of string properties and don't want to write the code to test each, you could always use Reflection to loop through the class's properties.
精彩评论