When working on Entity Framework Core, handling empty strings can sometimes be challenging, particularly when your application requires empty strings to be treated as nulls within the database. In particular cases, it is necessary that all string value properties which are empty should automatically be converted to null before they are saved into the database. This is especially important when dealing with legacy systems or migrating databases where this distinction matters.
This article presents a simple and fast method for changing an empty string to a null one right before any changes are made in EF Core. The solution involves overriding SaveChanges() method of your DbContext and iterating over the entity entries to see whether there exist any string properties with empty values.
Implementation
private void SetEmptyStringsToNull()
{
if (convertEmptyStringsToNull)
{
foreach (var entry in context.ChangeTracker.Entries())
{
if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
{
foreach (var property in entry.Properties.Where(x => x.Metadata.IsNullable &&
x.Metadata.ClrType == typeof(string) &&
x.CurrentValue is string currentValue &&
currentValue == string.Empty))
{
property.CurrentValue = null;
}
}
}
}
}
public int SaveChanges()
{
SetEmptyStringsToNull();
return context.SaveChanges();
}
Explanation SetEmptyStringsToNull Method:
This method checks if the convertEmptyStringsToNull flag is set to true. If so, it iterates through all the entries being tracked by the ChangeTracker in the current DbContext. For each entry in the Added or Modified state, it further checks all string properties to see if they are nullable and if their current value is an empty string. If an empty string is found, it sets the property value to null. SaveChanges Method:
This method overrides the standard SaveChanges method provided by Entity Framework Core. Before actually saving the changes to the database, it calls the SetEmptyStringsToNull method to ensure that any empty strings are converted to null. It then proceeds with the normal SaveChanges operation.