Getting mapped column names of properties in entity framework
You can get to the actual string "Person_Id" from the storage model, but you cannot identify that property/column as the foreign key. For that you would need Person_Id to exist in the conceptual model. I still don't quite understand why you wouldn't want it in the model, but here's how you would get it from the storage metadata:
using ( var context = new YourEntities() )
{
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 s as EntityType );
var personRightStorageMetadata = ( from m in entityProps where m.Name == "PersonRight" select m ).Single();
foreach ( var item in personRightStorageMetadata.Properties )
{
Console.WriteLine( item.Name );
}
}
For EF6
I could only find the mappings in DataSpace.CSSpace
(EntityTypeMapping
will map entities to tables, and ScalarPropertyMapping
will map scalar properties to columns):
using System.Data.Entity.Core.Mapping;
using System.Data.Entity.Core.Metadata.Edm;
// ...
using ( var db = new YourContext() )
{
var metadataWorkspace = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db)
.ObjectContext.MetadataWorkspace;
var itemCollection = ((StorageMappingItemCollection)metadataWorkspace
.GetItemCollection(DataSpace.CSSpace));
var entityMappings = itemCollection.OfType<EntityContainerMapping>().Single()
.EntitySetMappings.ToList();
var entityMapping = (EntityTypeMapping)entityMappings
.Where(e => e.EntitySet.ElementType.FullName == typeof(TEntity).FullName)
//or .Where(e => e.EntitySet.ElementType.Name == "YourEntityName")
.Single().EntityTypeMappings.Single();
var fragment = entityMapping.Fragments.Single();
var dbTable = fragment.StoreEntitySet;
Console.WriteLine($"Entity {entityMapping.EntityType.FullName} is mapped to table [{dbTable.Schema}].[{dbTable.Name}]");
var scalarPropsMap = entityMapping.Fragments.Single()
.PropertyMappings.OfType<ScalarPropertyMapping>();
foreach(var prop in scalarPropsMap)
Console.WriteLine($"Property {prop.Property.Name} maps to Column {prop.Column.Name}");
}
Out of curiosity I use the code above because System.Data.SqlClient.SqlBulkCopy
requires mapping between entity properties and table columns.