从 DbContext 和使用 Include() 方法检索 DbSet <T> 的通用方法 c#

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

我制作了这个检索所有数据的函数。

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

我有这个检索 DBSet T 的通用函数。

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

我可以创建一个通用函数来检索连接到一个 DBSet T 的所有数据吗?

提前致谢。

T 实体获取 DbSet Class 从上下文输入 DbSet<T>IQueryable<T>

在这个 IQueryable<T> 对象上可以在命名空间 System.Linq.[=22= 的帮助下执行多个操作,例如 Where()Include()orderBy() 等]

  • 使用Include()方法,传递所需的包含属性。

  • 对于并行处理,使用来自 System.Threading.Tasks

    的 TPL

试试这个:

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

几个月前我尝试做类似的事情,但我有 table名字。我留给你一些细节,你可以适应

您提取所有 table 和 select 的表单上下文,只有与您的 T 类型对应的 ClrType。

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

这是我的习惯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; }
}

然后您可以提取所有参考资料属性

var joinLookup = selectedTable.JoinTable.GetLookupForeignKey();

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

希望对你有所帮助

*** 编辑

如果您需要自定义包含 T,您可以使用 IIncludableQueryable<T, object>>

public static List<T> GetDbSet<T>(IIncludableQueryable<T, object>> include = null) where T : class
{
    using (VolunteerPlacementSystemDBEntities1 db = new VolunteerPlacementSystemDBEntities1())
    {
        IQueryable<T> query = db.Set<T>();

        if (includesFunc is not null)
            query = includesFunc(query);

        return query.ToList();
    }
}

感谢所有试图帮助我的人。 这是对我有用的解决方案。

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