Generic method to retrieve DbSet from DbContext

前端 未结 5 1221
长情又很酷
长情又很酷 2021-01-04 03:02

I\'m using the Entity Framework with a large database (made up of more than 200 tables).

Trying to create a generic method that returns the DbSet

5条回答
  •  鱼传尺愫
    2021-01-04 03:43

    I had the same requirement and solved it by using the following:

    public static void GetEntitiesGeneric()// where TEntity : System.Data.Entity.Core.Objects.DataClasses.EntityObject  <-- NO LONGER NEEDED
    {
        try
        {
            var key = typeof(TEntity).Name;
            var adapter = (IObjectContextAdapter)MyDbContext;
            var objectContext = adapter.ObjectContext;
            // 1. we need the container for the conceptual model
            var container = objectContext.MetadataWorkspace.GetEntityContainer(
                objectContext.DefaultContainerName, System.Data.Entity.Core.Metadata.Edm.DataSpace.CSpace);
            // 2. we need the name given to the element set in that conceptual model
            var name = container.BaseEntitySets.Where((s) => s.ElementType.Name.Equals(key)).FirstOrDefault().Name;
            // 3. finally, we can create a basic query for this set
            var query = objectContext.CreateQuery("[" + name + "]");
    
            // Work with your query ...
        }
        catch (Exception ex)
        {
            throw new ArgumentException("Invalid Entity Type supplied for Lookup", ex);
        }
    }
    

    The code was taken from Using Generics for Lookup Tables in Entity Framework and adapted for EF 6 using the DbContext (first part of the method where the objectcontext is extracted from the dbcontext

    Hope it helps

提交回复
热议问题