Raoul
Raoul

Reputation: 2063

Entity Framework 4 Code Only Get table name from MetaData for POCO domain object

Hi I am using Entity Framework code only from CTP4. My question is this: given the name of a domain class which is mapped using an EntityConfiguration how can I retrieve the table name for the mapped class at runtime? I'm assuming I need to be using the MetadataWorkspace on the ObjectContext, but finding it difficult to get up-to-date documentation. Any help or links would be much appreciated. Thanks.

Upvotes: 4

Views: 622

Answers (1)

Alexander Manekovskiy
Alexander Manekovskiy

Reputation: 3203

Yes you are right, all mapping information could be retrieved through MetadataWorkspace.

Below is the code to retireve table and schema names for 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 table name for Product class you have to create DbContext and use 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 that this is a perfect solution but as I used it before and it worked without issues.

Upvotes: 1

Related Questions