I need to do some trimming before saving various fields in our database. We're deserializing xml from another application into EF entities and then inserting them. There are few fields in the xml that exceed 4000 chars, and instead of using the TEXT data type, we'd like to trim them instead.
My thought was to inspect MetadataWorkspace
and DbChangeTracker
inside MyDbContext.SaveChanges()
to find any nvarchar(4000)
entity properties and trim any string values that are longer than 4000. But I have no idea how to approach this. I couldn't find any relevant documentation. I saw a few related questions, but none went into any detail or provided any code samples.
Here's what I've got so far:
public override int SaveChanges()
{
//TODO: trim strings longer than 4000 where type is nvarchar(max)
MetadataWorkspace metadataWorkspace =
((IObjectContextAdapter) this).ObjectContext.MetadataWorkspace;
ReadOnlyCollection<EdmType> edmTypes =
metadataWorkspace.GetItems<EdmType>(DataSpace.OSpace);
return base.SaveChanges();
}
Solution
Here's my solution based on @GertArnold's answer.
// get varchar(max) properties
var entityTypes = metadataWorkspace.GetItems<EntityType>(DataSpace.CSpace);
var properties = entityTypes.SelectMany(type => type.Properties)
.Where(property => property.TypeUsage.EdmType.Name == "String"
&& property.TypeUsage.Facets["MaxLength"].Value.ToString() == "Max"
// special case for XML columns
&& property.Name != "Xml")
.Select(
property =>
Type.GetType(property.DeclaringType.FullName)
.GetProperty(property.Name));
// trim varchar(max) properties > 4000
foreach (var entry in ChangeTracker.Entries())
{
var entity = entry.Entity;
var entryProperties =
properties.Where(prop => prop.DeclaringType == entity.GetType());
foreach (var entryProperty in entryProperties)
{
var value =
((string) entryProperty.GetValue(entity, null) ?? String.Empty);
if (value.Length > 4000)
{
entryProperty.SetValue(entity, value.Substring(0, 4000), null);
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…