ORM – Entity Framework 4 only obtains the table name of poco domain object from metadata

Hi, I only use entity framework code from ctp4 My question is: given the name of the domain class mapped using entityconfiguration, how do I retrieve the table name of the mapped class at run time? I suppose I need to use metadataworkspace on objectcontext, but I find it difficult to get the latest documents Any help or links will be appreciated thank you.

Solution

Yes, you are right. You can retrieve all mapping information through metadata workspace

The following is the code to exit the table and schema name of the product class:

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; }
}

Now, to retrieve the table name of the product class, you must create a dbcontext and use the following code:

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").
}

I doubt this is a perfect solution, but as I used it before, and it has no problem

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>