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.
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
}
Not that I'm aware of.
You could possibly write a class that inherited from ObjectContext
and override SaveChanges()
to do that and use that instead of ObjectContext
in your x.objectlayer.cs / x.designer.cs