查找属性的数据库字段名称 [英] Find the database field name of a property
问题描述
我有一个EntityFramework模型,其属性为 Prop
,映射到表中的一个字段 - 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
的列表。其中一个确实是 Prop
,但它只包含属性的名称,而不是数据库中的字段名。
I followed the suggestion in this answer and received a list of EntityType
s. 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
和 Field
。使用 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()
});
这篇关于查找属性的数据库字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!