【问题标题】:Entity Framework 4 Code Only Get table name from MetaData for POCO domain objectEntity Framework 4 Code Only 从元数据中获取 POCO 域对象的表名
【发布时间】:2011-04-18 08:38:30
【问题描述】:

您好,我只使用来自 CTP4 的实体框架代码。我的问题是:给定使用 EntityConfiguration 映射的域类的名称,我如何在运行时检索映射类的表名?我假设我需要在 ObjectContext 上使用 MetadataWorkspace,但发现很难获得最新的文档。任何帮助或链接将不胜感激。谢谢。

【问题讨论】:

    标签: orm entity-framework-4 code-first ef4-code-only


    【解决方案1】:

    是的,您是对的,所有映射信息都可以通过 MetadataWorkspace 检索。

    以下是为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").
    }
    

    我怀疑这是一个完美的解决方案,但正如我之前使用过的那样,它可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 2012-04-03
      • 2011-04-07
      • 2011-03-31
      • 2023-03-27
      • 2011-01-06
      相关资源
      最近更新 更多