2010-09-28 22 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"). 
} 

我怀疑这是一个完美的解决方案,但正如我以前使用它,它没有问题的工作。

相关问题