2

I am building an MVC 4 app. I have view that has a dropdown that needs to display all the tables (entities) used..

How can I do that? I am using EF 5 code first with configurations.

Any help would be appreciated.

Thanks

user2206329
  • 2,792
  • 10
  • 54
  • 81

2 Answers2

7

This code will get them for you, of course the ones that has been imported to your EDM which necessarily is not all the tables in your data store.

var tableNames = context.MetadataWorkspace.GetItems(DataSpace.SSpace)
                        .Select(t => t.Name)
                        .ToList();

For code first:

using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Data.Entity.Infrastructure;

...

using (dbcontext context = new TestContext())
{
   ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
   MetadataWorkspace workspace = objContext.MetadataWorkspace;
   IEnumerable<EntityType> tables = workspace.GetItems<EntityType>(DataSpace.SSpace);

}
Radenko Zec
  • 7,659
  • 6
  • 35
  • 39
  • there is no such thing as MetadataWorkspace in my context – user2206329 Jan 17 '14 at 10:12
  • Radenko - Can I ask you one more question, I have added a custom attribute to some entities called DoNotAudit. How do I only get a list of tables that don't have an attribute? – user2206329 Jan 17 '14 at 13:01
2

This work very well for me on EF 6

        public List<string> EntityNames()
        {
            ObjectContext objContext = ((IObjectContextAdapter)myDbContext).ObjectContext;
            MetadataWorkspace workspace = objContext.MetadataWorkspace;
            IEnumerable<EntityType> tables = workspace.GetItems<EntityType>(DataSpace.SSpace);

            List<string> lst = new List<string>();
            foreach (var table in tables)
            {
                var entityName = table.FullName.Replace("CodeFirstDatabaseSchema.", "");
                lst.Add($"{entityName}");
            }

            return lst;
        }
gorums
  • 1,567
  • 13
  • 5