Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an option to make Entity Framework revert empty strings to null?

I am using an ADO.NET Entity-Framework ObjectContext to access my data store.

I want the if values are set with empty strings, they should automatically become null.

like image 690
Shimmy Weitzhandler Avatar asked Jul 13 '09 14:07

Shimmy Weitzhandler


2 Answers

If your using Entity Framework 4, you can use T4 templates to accomplish this. Just place this in the getter of each string property in your .tt template file, and it will replace empty strings with null and automatically trim strings. No need to use reflection.

<#+ if (primitiveProperty.TypeUsage.ToString().Split('.').Last() == "String") { #>
   if (value == "") value = null;
   else value = value.Trim();
<#+ } #>
like image 177
Sterling Nichols Avatar answered Oct 14 '22 05:10

Sterling Nichols


I actually found a better way to this, it's actually built in the system, plus it uses the internal ordinal metadata of the entities which are loaded anyway (I haven't tested the performance difference, but this should be hell of a lot faster than reflection):

private const string StringType = "String";
private const EntityState SavingState = EntityState.Added | EntityState.Modified;
public override int SaveChanges()
{
  //when using on ObjectContext replace 'objectContext' with 'this',
  //and override SaveChanges(SaveOptions options) instead:

  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(); //SaveChanges(options) on ObjectContext
}
like image 20
Shimmy Weitzhandler Avatar answered Oct 14 '22 06:10

Shimmy Weitzhandler