Search code examples
c#entity-frameworkentity

Generic method to retrieve DbSet <T> from DbContext and Using Include() method c#


I made this function that retrieves all the data.

public static List<Volunteer> GetAllVolunteers()
{
    using (VolunteerPlacementSystemDBEntities1 db = new VolunteerPlacementSystemDBEntities1())
    {
        return db.Volunteers.**Include(v => v.roleForVolunteers).Include(v => v.VolunteerOffers)
                         .Include("VolunteerOffers.daysForAVolunteers")**.ToList();
    }
}

And I have this generic function that retrieves DBSet T.

public static List<T> GetDbSet<T>() where T : class
{
    using (VolunteerPlacementSystemDBEntities1 db = new VolunteerPlacementSystemDBEntities1())
    {
        return db.GetDbSet<T>().ToList();
    }
}

Can I make a generic function that will retrieve all the data that connect to one DBSet T?

Thanks in advance.


Solution

  • Thanks to everyone who tried to help me. This is the solution that worked for me.

      public static List<T> GetDbSetWithIncludes<T>(string[] includes) where T : class
        {
            using (VolunteerPlacementSystemDBEntities1 db = new VolunteerPlacementSystemDBEntities1())
            {
                db.Configuration.LazyLoadingEnabled = false;
                return IncludeMultiple<T>(db.GetDbSet<T>(), includes).ToList();
            }
        }
    
    
     public static IQueryable<T> IncludeMultiple<T>(IQueryable<T> query, string[] includes)where T : class
            {
                if (includes != null)
                {
                    query = includes.Aggregate(query, (current, include) =>
                    current.Include(include));
                }
                return query;
            }