一旦你有了类型,问题是如何获得相应的DbSet 。 EF Core目前不提供类似于DbSet非genericsSet(Type)方法,主要是因为没有非genericsDbSet类。 但是你可以通过使用一些EF Core内部结构获得相应的DbSet作为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); } }
或通过reflection调用通用的Set方法:
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)); 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(...)
EF Core不再具有非generics.set方法,但是此扩展类使得使用动态linq基于字符串查询表变得容易
public static class DbContextExtensions { public static IQueryable
}
用法:
IQueryable query = db.Set("TableName"); // Filter against "query" variable below... List result = query.ToList(); // or use further dynamic Linq IQueryable query = db.Set("TableName").Where("t => t.TableFilter == \"MyFilter\"");