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

帅比萌擦擦* 提交于 2019-11-28 10:32:44

问题


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


来源:https://stackoverflow.com/questions/21182716/how-to-get-a-list-of-all-entities-in-ef-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!