如何在运行时检查EF模型元数据? [英] How to inspect EF model metadata at runtime?

查看:96
本文介绍了如何在运行时检查EF模型元数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的数据库中保存各种字段之前,我需要进行一些修改。我们将xml从另一个应用程序反序列化为EF实体,然后插入它们。 xml中有几个字段超过4000个字符,而不是使用TEXT数据类型,我们希望修改它们。



我的想法是检查 MetadataWorkspace DbChangeTracker 里面 MyDbContext.SaveChanges()任何 nvarchar(4000)实体属性并修剪长于4000的任何字符串值。但是我不知道如何处理这个。我找不到任何相关文件。我看到一个几个相关问题,但没有一个进入任何细节或提供任何代码示例。



以下是我到目前为止:

  public override int SaveChanges()
{
// TODO:trim strings than 4000 where type is nvarchar(max)
MetadataWorkspace metadataWorkspace =
(IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
ReadOnlyCollection< EdmType> edmTypes =
metadataWorkspace.GetItems&EdimType>(DataSpace.OSpace);

return base.SaveChanges();
}

解决方案



这是基于@ GertArnold的答案的解决方案。

  // 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
// XML列的特殊情况
&& property.Name!=Xml)
.Select(
property =>
Type.GetType(property.DeclaringType.FullName)
.GetProperty(property.Name));

//修剪varchar(max)属性> 4000
foreach(ChangeTracker.Entries()中的var entry)
{
var entity = entry.Entity;
var entryProperties =
properties.Where(prop => prop.DeclaringType == entity.GetType());
foreach(entryProperties中的var entryProperty)
{
var value =
((string)entryProperty.GetValue(entity,null)?String.Empty);
if(value.Length> 4000)
{
entryProperty.SetValue(entity,value.Substring(0,4000),null);
}
}
}


解决方案

您可以通过这段代码找到属性:

  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();

诀窍是通过 BuiltInTypeKind.EntityType从模型中提取实体类型并将它们转换为 EntityType 以访问属性。一个EdmProperty有一个属性 DeclaringType ,显示它们属于哪个实体。


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);
        }
    }
}

解决方案

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.

这篇关于如何在运行时检查EF模型元数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆