2015-02-09 51 views
2

我遇到這樣一種情況,即我的表名與使用EF 6中的映射的模型上的類屬性不同。模型和數據庫像這樣:從實體框架6數據庫中的數據庫中獲取列名稱首先在映射中使用不同的屬性名稱

public class AGENTMap : EntityTypeConfiguration<AGENT> 
{ 
    public AGENTMap() 
    { 
     // Primary Key 
     this.HasKey(t => new {t.AgentCode }); 

     // Properties 
     this.Property(t => t.AgentCode) 
      .HasMaxLength(10); 

     this.Property(t => t.AgentName) 
      .HasMaxLength(30); 


     // Table & Column Mappings 
     this.ToTable("AGENT"); 
     this.Property(t => t.agent_cd).HasColumnName("agent_cd"); 
     this.Property(t => t.agent_nm).HasColumnName("agent_nm"); 
    } 
} 

它等同於具有這些屬性的AGENT類。 問題是,當我試圖讓使用此代碼段中的主鍵:

ObjectContext objectContext = ((IObjectContextAdapter)_context).ObjectContext; 
     ObjectSet<TEntity> objSet = objectContext.CreateObjectSet<TEntity>(); 
     IEnumerable<string> keyNames = objSet.EntitySet.ElementType.KeyMembers 
      .Where(p => p.MetadataProperties.Any(m => m.PropertyKind == PropertyKind.Extended 
           && Convert.ToString(m.Value) == "Identity")) 
                .Select(e => e.Name).ToList(); 

     return keyNames; 

它返回的屬性名稱的映射類。我想獲得「agent_cd」..這是數據庫的列名..是否有一種方法在EF6中獲取Db上的確切列名?

回答

2

羅文米勒wrote another blog post準確說明如何獲得列名EF 6

public static string GetColumnName(Type type, string propertyName, DbContext context) 
{ 
    var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace; 

    // Get the part of the model that contains info about the actual CLR types 
    var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace)); 

    // Get the entity type from the model that maps to the CLR type 
    var entityType = metadata 
      .GetItems<EntityType>(DataSpace.OSpace) 
      .Single(e => objectItemCollection.GetClrType(e) == type); 

    // Get the entity set that uses this entity type 
    var entitySet = metadata 
     .GetItems<EntityContainer>(DataSpace.CSpace) 
     .Single() 
     .EntitySets 
     .Single(s => s.ElementType.Name == entityType.Name); 

    // Find the mapping between conceptual and storage model for this entity set 
    var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace) 
      .Single() 
      .EntitySetMappings 
      .Single(s => s.EntitySet == entitySet); 

    // Find the storage entity set (table) that the entity is mapped 
    var tableEntitySet = mapping 
     .EntityTypeMappings.Single() 
     .Fragments.Single() 
     .StoreEntitySet; 

    // Return the table name from the storage entity set 
    var tableName = tableEntitySet.MetadataProperties["Table"].Value ?? tableEntitySet.Name; 

    // Find the storage property (column) that the property is mapped 
    var columnName = mapping 
     .EntityTypeMappings.Single() 
     .Fragments.Single() 
     .PropertyMappings 
     .OfType<ScalarPropertyMapping>() 
     .Single(m => m.Property.Name == propertyName) 
     .Column 
     .Name; 

    return tableName + "." + columnName; 
} 
相關問題