简体   繁体   中英

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

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

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM