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.
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);
}