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

Time:05-24

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.

CodePudding user response:

Some month ago i try to do somthing like that, but i have tableName. I leave you some detail, that you can adapt

You extract form context all your table and select only the ClrType corrispond with your T type.

var selectedTable = contextDb.Model
            .GetEntityTypes()
            .Select(x => new TableSpecification // Custom class
            {
                TableName = x.GetTableName(),
                ClrType = x.ClrType,
                JoinTable = x.GetForeignKeys(),
                JoinTableProp = x.GetForeignKeyProperties(),
                NavigationProp = x.GetNavigations(),
                ColumnsTable = null
            })
           .Where(// where ClrType)
           .Distinct()
           .FirstOrDefault();

This is my custom class

using Microsoft.EntityFrameworkCore.Metadata;

using System;
using System.Collections.Generic;

namespace Seac.CRM.DbInfrastructure.Model.Context;

public class TableSpecification
{
    public string TableName { get; init; }
    public Type ClrType { get; init; }
    public IEnumerable<IForeignKey> JoinTable { get; init; }
    public IEnumerable<IProperty> JoinTableProp { get; init; }
    public IEnumerable<INavigation> NavigationProp { get; init; }
    public IEnumerable<IProperty> ColumnsTable { get; init; }
}

then you can extract all your reference property

var joinLookup = selectedTable.JoinTable.GetLookupForeignKey();

foreach (var lookup in joinLookup)
   queryable = queryable.Include(lookup.PrincipalEntityType.Name.Split(".").Last());

I wish that can help you.

CodePudding user response:

Get DbSet for the T Entity Class Type from context as DbSet or IQueryable<T>.

On this IQueryable<T> object can perform multiple operations like Where(), Include(), orderBy() etc.

  • With Include() method, pass on required included properties.

  • For Parallel processing use TPL from System.Threading.Tasks

Try this:

public static List<T> GetDbSet<T>(string[] includeProperties) where T : class
{
    using (VolunteerPlacementSystemDBEntities1 db = new VolunteerPlacementSystemDBEntities1())
    {
        IQueryable<T> query = db.Set<T>();

        Parallel.ForEach(inlcudeProperties, includeProperty => {
           query.Include(includeProperty);
        });

        return query.ToList();
    }
}
  • Related