As the question states, anyone know how to get the entity table name in entity framework 7?
I have the code to do this in entity framework 6.1 (from another site, cant find link), but none of the interfaces/objects seem to be referenced in entity framework 7.
Code for 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;
}
The only thing you need to do now to achieve the same is this:
public string GetTableName(Type type)
{
return this.Model.GetEntityType(type).SqlServer().TableName;
}
PS: I'm assuming this method is declared in your DbContext
class, otherwise change the this
keyword for your DbContext
instance.
GetEntityType
was renamed to FindEntityType
. You can find more info in this link
return this.Model.FindEntityType(type).SqlServer().TableName;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With