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

后端 未结 8 1026
时光说笑
时光说笑 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条回答
  •  不要未来只要你来
    2021-02-06 10:00

    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
    }
    

提交回复
热议问题