How to get EF to save blank lines as NULL?

In my domain there is no important difference between NULL and an empty string. How to make EF ignore the difference between them and always keep the empty string as NULL?

+4
source share
3 answers

An empty string is not the default for the string property, so it means your code sets empty strings somewhere. In this case, you are responsible for this.

If you use the code first with POCOs, you can use a custom setter:

private string _myProperty; public string MyProperty { get { return _myProperty; } set { if (value == String.Empty) { _myProperty = null; } else { _myProperty = value; } } } 
+5
source

Here is a function that I put in my subclass of DbContext that replaces empty or whitespace lines with zero.

I still haven't optimized it, so any performance hints would be greatly appreciated.

 private const string StringType = "String"; private const EntityState SavingState = EntityState.Added | EntityState.Modified; public override int SaveChanges() { var objectContext = ((IObjectContextAdapter)this).ObjectContext; var savingEntries = objectContext.ObjectStateManager.GetObjectStateEntries(SavingState); foreach (var entry in savingEntries) { var curValues = entry.CurrentValues; var fieldMetadata = curValues.DataRecordInfo.FieldMetadata; var stringFields = fieldMetadata.Where(f => f.FieldType.TypeUsage.EdmType.Name == StringType); foreach (var stringField in stringFields) { var ordinal = stringField.Ordinal; var curValue = curValues[ordinal] as string; if (curValue != null && curValue.All(char.IsWhiteSpace)) curValues.SetValue(ordinal, null); } } return base.SaveChanges(); } 

Optimization:

  • Define a property of type string different way than comparing strings. I tried to find some numbering of built-in types, but did not find
  • Lines of cache fields for types (may not be needed, you will have to decompile and see what the original impl does.
  • The result of the order by the type of object, the type of repeated copy with repetition, if the next iterated object is of the same type, use the previous metadata, again, if the metadata is anyway there, the performance is cheaper, since it
  • Limit the length of the string to check for space - i.e. if the length of the string is> x, skip checking its space bar or not

I use Silverlight, and TextBox es in the user interface set all row properties to empty lines.

I tried setting:

 <TextBox Text="{Binding MyStringProperty, Mode=TwoWay, ValidatesOnDataErrors=True, TargetNullValue=''}"/> 

But it didn’t help much.

+3
source

This is not a Framework Framework.

You must do this in your repository or database using triggers.

Or do it from the very beginning (for example, when data arrives, user interface, external source, etc.)

0
source

All Articles