how to get a list of all entities in EF 5?

2019-01-29 01:50发布

问题:

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

回答1:

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

}


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