Let’s assume you have the following model with a non-required string property. While you are trying to save this object in your Db using Entity Framework you may see that the string property in your record will not be Null
but (empty string).
To overcome this you need to override SaveChages
, SaveChangesAsync
method in your DbContext indicating that all string properties with empty values should be of Null
value.
The following code may do the trick:
public override Task<int> SaveChangesAsync() { var objContext = ((IObjectContextAdapter)this).ObjectContext; var entries = objContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified) .Select(entry => entry.Entity); var str = typeof(string).Name; foreach (var entity in entries) { var properties = from p in entity.GetType().GetProperties() where p.PropertyType.Name == str select p; var items = from item in properties let value = (string)item.GetValue(entity, null) where value != null && value.Trim().Length == 0 select item; foreach (var item in items) { item.SetValue(entity, null, null); } } return base.SaveChangesAsync(); }
The reason why EF will not replace an empty string on a property with a null value appears to be a consequence of the data validation feature which both EF5 and EF6 use by default on DbContext.SaveChanges().