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.
If your using Entity Framework 4, you can use T4 templates to accomplish this. Just place this in the getter of each string property in your .tt template file, and it will replace empty strings with null and automatically trim strings. No need to use reflection.
<#+ if (primitiveProperty.TypeUsage.ToString().Split('.').Last() == "String") { #>
if (value == "") value = null;
else value = value.Trim();
<#+ } #>
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With