首先您需要从名称中获取实体的类型(如果您有类型,则直接使用它)。您可以为此使用反射,但 EF Core 的正确方法可能是使用 FindEntityType 方法。
一旦有了类型,问题就是如何获取对应的DbSet<T>。 EF Core 目前不提供类似于 EF6 的非泛型 Set(Type) 方法,主要是因为没有非泛型 DbSet 类。但是您仍然可以通过使用一些 EF Core 内部来获得对应的 DbSet<T> 为 IQueryable:
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore.Internal;
namespace Microsoft.EntityFrameworkCore
{
public static partial class CustomExtensions
{
public static IQueryable Query(this DbContext context, string entityName) =>
context.Query(context.Model.FindEntityType(entityName).ClrType);
public static IQueryable Query(this DbContext context, Type entityType) =>
(IQueryable)((IDbSetCache)context).GetOrAddSet(context.GetDependencies().SetSource, entityType);
}
}
或者(最好)通过反射调用通用的Set<T>方法:
using System;
using System.Linq;
using System.Reflection;
namespace Microsoft.EntityFrameworkCore
{
public static partial class CustomExtensions
{
public static IQueryable Query(this DbContext context, string entityName) =>
context.Query(context.Model.FindEntityType(entityName).ClrType);
static readonly MethodInfo SetMethod = typeof(DbContext).GetMethod(nameof(DbContext.Set), Type.EmptyTypes);
public static IQueryable Query(this DbContext context, Type entityType) =>
(IQueryable)SetMethod.MakeGenericMethod(entityType).Invoke(context, null);
}
}
在这两种情况下,您都可以使用如下内容:
db.Query("Namespace.MyTable").Where(...)
或
db.Query(typeof(MyTable)).Where(...)