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

后端 未结 8 896
时光说笑
时光说笑 2021-02-06 09:30

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.

相关标签:
8条回答
  • 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
    }
    
    0 讨论(0)
  • 2021-02-06 10:04

    Not that I'm aware of.

    You could possibly write a class that inherited from ObjectContext and override SaveChanges() to do that and use that instead of ObjectContext in your x.objectlayer.cs / x.designer.cs

    0 讨论(0)
提交回复
热议问题