找到一个属性的数据库字段名属性、字段名、数据库

2023-09-06 11:00:27 作者:ら.⒉O味道狠甜

我有一个属性道具映射到一个字段在表中的EntityFramework模型 - PropField 。我想找到的字段的名称( PropField )在运行时。

I have an EntityFramework model with a property Prop that is mapped to a field in the table - PropField. I want to find the field's name (PropField) at runtime.

我跟着这个答案的建议,并获得的EntityType 秒。其中之一是确实的道具,但它仅包含属性的名称,而不是在数据库中的字段名。

I followed the suggestion in this answer and received a list of EntityTypes. One of them is indeed of Prop, but it only contains the property's name, not the field name in the database.

我访问 DataSpace.CSpace 的元数据,并获得数据库字段列表。 PropField 确实是有的,但还有的 PropField 没有任何关联和字段。使用 DataSpace.CSSpace 未返回任何有意义的东西。

I accessed the DataSpace.CSpace metadata, and received a list of database fields. PropField is indeed there, but there's no association between PropField and Field. Using DataSpace.CSSpace didn't return anything meaningful.

我如何才能找到字段的名字?

How can I find the field's name?

推荐答案

建立在这个问题的答案我想出了这个非常哈克反思的解决方案 - 领域显然是有的,但我找不到访问他们的任何合法的方式。我只用它的单元测试,所以没有什么大不了的,如果它打破了。

Building on that answer I came up with this extremely hacky reflection solution - the fields are clearly there, but I can't find any legitimate way to access them. I'm only using it for unit testing, so no big deal if it breaks.

    var objectContext = ((IObjectContextAdapter)context).ObjectContext;
    var storageMetadata = ((EntityConnection)objectContext.Connection).GetMetadataWorkspace().GetItems(DataSpace.SSpace);
    var entityProps = (from s in storageMetadata where s.BuiltInTypeKind == BuiltInTypeKind.EntityType select (System.Data.Entity.Core.Metadata.Edm.EntityType)s);
    var entityName = "OrderItem";
    var entityStorageMetadata = (from m in entityProps where m.Name == entityName select m).Single();
    var pi = typeof(System.Data.Entity.Core.Metadata.Edm.EntityType).GetProperty("ForeignKeyBuilders", BindingFlags.NonPublic | BindingFlags.Instance);
    var fkBuilders = (IEnumerable<object>)pi.GetValue(entityStorageMetadata);
    Type builderType = fkBuilders.First().GetType();
    var builderProps = builderType.GetProperties();

    var fullPropsToColumns = fkBuilders.Select(x => new
    {
        PropertyName = builderProps.First(p => p.Name == "Name").GetValue(x).ToString().Split('_')[1],
        FieldName = ((IEnumerable<object>)builderProps.First(p => p.Name == "DependentColumns").GetValue(x)).First().ToString()
    });
 
精彩推荐
图片推荐