Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

entity framework 4 - How to inspect EF model metadata at runtime?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can find the properties by this piece of code:

var varchars = context.MetadataWorkspace.GetItemCollection(DataSpace.CSpace)
    .Where(gi => gi.BuiltInTypeKind == BuiltInTypeKind.EntityType)
    .Cast<EntityType>()
    .SelectMany(entityType => entityType.Properties
        .Where(edmProperty => edmProperty.TypeUsage.EdmType.Name == "String")
        .Where(edmProperty => (int)(edmProperty.TypeUsage.Facets["MaxLength"]
            .Value) >= 4000))
    .ToList();

The trick is to extract the entity types from the model by BuiltInTypeKind.EntityType and cast these to EntityType to get access to the Properties. An EdmProperty has a property DeclaringType which shows to which entity they belong.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...