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

后端 未结 8 1023
时光说笑
时光说笑 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
    2021-02-06 09:49

    Here is a solution for Entity Framework Core (tested in V2). Had to bang my way through the API due to limited documentation so there might be other ways to accomplish the same thing. Note that the original objects are modified using this method.

    public override int SaveChanges()
    {
        ConvertWhitespaceToNulls();
        return base.SaveChanges();
    }
    
    
    private void ConvertWhitespaceToNulls()
    {
        var entityEntries = this.ChangeTracker
            .Entries()
            .Where(x => x.State == EntityState.Modified || x.State == EntityState.Added && x.Entity != null);
    
        foreach (var e in entityEntries)
            foreach (var currentValue in e.CurrentValues.Properties.Where(p => p.ClrType == typeof(string) && p.IsNullable))
                if (string.IsNullOrWhiteSpace((string) currentValue.FieldInfo.GetValue(e.Entity)))
                    currentValue.FieldInfo.SetValue(e.Entity, null);
    }
    

提交回复
热议问题