正如问题所述,任何人都知道如何在实体框架7中获取实体表名称?
我有在实体框架6.1中执行此操作的代码(来自另一个站点,无法找到链接),但实体框架7中似乎没有引用任何接口/对象。
EF6.1的代码
public string GetTableName(Type type)
{
var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
var entityType = metadata.GetItems<EntityType>(DataSpace.OSpace).Single(e => objectItemCollection.GetClrType(e) == type);
var entitySet = metadata.GetItems(DataSpace.CSpace).Where(x => x.BuiltInTypeKind == BuiltInTypeKind.EntityType).Cast<EntityType>().Single(x => x.Name == entityType.Name);
var entitySetMappings = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace).Single().EntitySetMappings.ToList();
EntitySet table = null;
var mapping = entitySetMappings.SingleOrDefault(x => x.EntitySet.Name == entitySet.Name);
if (mapping != null)
{
table = mapping.EntityTypeMappings.Single().Fragments.Single().StoreEntitySet;
}
else
{
mapping = entitySetMappings.SingleOrDefault(x => x.EntityTypeMappings.Where(y => y.EntityType != null).Any(y => y.EntityType.Name == entitySet.Name));
if (mapping != null)
{
table = mapping.EntityTypeMappings.Where(x => x.EntityType != null).Single(x => x.EntityType.Name == entityType.Name).Fragments.Single().StoreEntitySet;
}
else
{
var entitySetMapping = entitySetMappings.Single(x => x.EntityTypeMappings.Any(y => y.IsOfEntityTypes.Any(z => z.Name == entitySet.Name)));
table = entitySetMapping.EntityTypeMappings.First(x => x.IsOfEntityTypes.Any(y => y.Name == entitySet.Name)).Fragments.Single().StoreEntitySet;
}
}
return (string)table.MetadataProperties["Table"].Value ?? table.Name;
}
答案 0 :(得分:13)