加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

orm – 实体框架4仅代码从MetaData获取POCO域对象的表名

发布时间:2020-12-15 02:21:52 所属栏目:Java 来源:网络整理
导读:嗨,我只使用来自CTP4的实体框架代码.我的问题是:给定使用EntityConfiguration映射的域类的名称,如何在运行时检索映射类的表名?我假设我需要在ObjectContext上使用MetadataWorkspace,但发现很难获得最新的文档.任何帮助或链接将不胜感激.谢谢. 解决方法 是
嗨,我只使用来自CTP4的实体框架代码.我的问题是:给定使用EntityConfiguration映射的域类的名称,如何在运行时检索映射类的表名?我假设我需要在ObjectContext上使用MetadataWorkspace,但发现很难获得最新的文档.任何帮助或链接将不胜感激.谢谢.

解决方法

是的,你是对的,可以通过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").
}

我怀疑这是一个完美的解决方案,但正如我之前使用它并且它没有问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读