gpt4 book ai didi

.net - Entity Framework 4.1 - 如何获取生成的 poco 对象的列名

转载 作者:行者123 更新时间:2023-12-01 15:03:59 29 4
gpt4 key购买 nike

我正在使用 Entity Framework 4.1,一个 edmx 映射文件用于使用 T4 模板生成 poco 类。

如何从我的 poco 实体属性的对象上下文中获取数据库列的名称(如果可能的话)。

我相信属性和列之间的映射应该在其中一个容器中:

var container = objectContext.MetadataWorkspace
.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace);
...

但我无法识别 CSpase 和 SSpace 之间的链接,看起来 CSSpase 可以完成这项工作,但这个容器是空的。

有什么想法吗?

最佳答案

我使用了混合方法来获取映射信息(我们必须为某些类型实现自定义数据读取器/写入器):

  1. 首先获取 EntityType 对象以提取您的 POCO 类型的元信息:

    public static EntityType GetEntityTypeForPoco(this ObjectContext context, 
    Type pocoEntityType)
    {
    EntityType entityType
    = context.MetadataWorkspace.GetItem<EntityType>
    (pocoEntityType.FullName, DataSpace.OSpace);

    return (EntityType)context.MetadataWorkspace
    .GetEdmSpaceType((StructuralType)entityType);
    }
  2. 读取映射XML文档:这部分基本上是硬编码的,映射xml文档保存在edmx文件所在的程序集中,它叫做[your_edmx_file_name].msl

    currentMslSchemaDocument = new StreamReader(
    Assembly.GetExecutingAssembly().
    GetManifestResourceStream(CurrentMslSchemaDocumentName)
    ).ReadToEnd();
  3. 从 XML 文档中读取属性到列的映射:

    var mappingFragments = MslSchemaDocument
    .Descendants(XName.Get(ElementNameEntityTypeMapping, NamespaceNameMsl))
    .Where(mp => (mp.Attributes(AttributeNameTypeName).Any()
    && mp.Attribute(AttributeNameTypeName).Value == entityTypeModelName));

    if (mappingFragments.Count() == 0)
    {
    throw new Exception(String.Format("Entity mapping {0} is not found in the given schema stream", entityTypeModelName));
    }

    //theoretically could be several fragments mapping one entity ytpe to several table
    XElement mappingFragment = mappingFragments.First();

    string tableName = mappingFragment.Descendants(XName.Get(ElementNameMappingFragment, NamespaceNameMsl))
    .First().Attribute(AttributeNameStoreEntitySet).Value;

    List<KeyValuePair<string, string>> propertyColumnMappingList = new List<KeyValuePair<string, string>>();

    foreach (var xScalarProperty in mappingFragment.Descendants(XName.Get(ElementNameScalarProperty, NamespaceNameMsl)))
    {
    propertyColumnMappingList.Add(new KeyValuePair<string, string>(xScalarProperty.Attribute(AttributeNameName).Value,
    xScalarProperty.Attribute(AttributeNameColumnName).Value));
    }

关于.net - Entity Framework 4.1 - 如何获取生成的 poco 对象的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7713676/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com