2010-09-28 48 views
4

嗨,我只使用CTP4實體框架代碼。我的問題是這樣的:給定使用EntityConfiguration映射的域類的名稱如何在運行時檢索映射類的表名?我假設我需要在ObjectContext上使用MetadataWorkspace,但發現很難獲得最新的文檔。任何幫助或鏈接將不勝感激。謝謝。Entity Framework 4 Code Only從MetaData獲取POCO域對象的表名

回答

1

是的你是對的,所有的映射信息都可以通過MetadataWorkspace獲取。

下面是retireve表,架構名稱爲Product類的代碼:

public class Product 
{ 
    public Guid Id { get; set; } 
    public string Name { get; set; } 
} 

public class ProductConfiguration : EntityTypeConfiguration<Product> 
{ 
    public ProductConfiguration() 
    { 
     HasKey(e => e.Id); 

     Property(e => e.Id) 
      .HasColumnName(typeof(Product).Name + "Id"); 

     Map(m => 
     { 
      m.MapInheritedProperties(); 
      m.ToTable("ProductsTable"); 
     }); 

     Property(p => p.Name) 
      .IsRequired() 
      .IsUnicode(); 
    } 
} 

public class Database : DbContext 
{ 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Configurations.Add(new ProductConfiguration()); 
    } 

    public DbSet<Product> Products { get; set; } 
} 

現在,爲Product類檢索表的名字你必須創建的DbContext和使用下面的代碼:

using(var dbContext = new Database()) 
{ 
    var adapter = ((IObjectContextAdapter)dbContext).ObjectContext; 
    StoreItemCollection storageModel = (StoreItemCollection)adapter.MetadataWorkspace.GetItemCollection(DataSpace.SSpace); 
    var containers = storageModel.GetItems<EntityContainer>(); 

    EntitySetBase productEntitySetBase = containers.SelectMany(c => c.BaseEntitySets.Where(bes => bes.Name == typeof(Product).Name)).First(); 

    // Here are variables that will hold table and schema name 
    string tableName = productEntitySetBase.MetadataProperties.First(p => p.Name == "Table").Value.ToString(); 
    string schemaName = productEntitySetBase.MetadataProperties.First(p => p.Name == "Schema"). 
} 

我懷疑這是一個完美的解決方案,但正如我以前使用它,它沒有問題的工作。