2011-01-25 15 views
3

すべての変更を含むコレクションを保存しているときに、空の文字列をNULLとして確実に保存する方法を教えてください。私はlinq、wpf、wcfを使用しています。空文字列の代わりにNULLを格納する

空白の場合は、レコードの各レコードとレコードの各プロパティを反復してnullにする必要はありません。

答えて

1

WCF DataContractで[OnSerializing]イベントを実装すると、String.Emptyをチェックしてnullに変更できます。 EG:

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

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

そして、あなたは文字列プロパティの多くを持っており、それぞれをテストするためのコードを記述したくない場合、あなたは常にクラスのプロパティをループするためにリフレクションを使用することができます。

2

あなたは次のような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> 
を次のようにあなたのコントロールにこれをバインド
関連する問題