You can override the Query
method of DbContext.
First,create a custom Query method:
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);
}
Then, you need to store the table names and types
of all the tables involved in the Dictionary
.
Dictionary<string, Type> TableTypeDictionary = new Dictionary<string, Type>()
{
{ "Teachers", typeof(Teachers) },//store the tables name and type.
{ "Students", typeof(Students) },
{ "Product", typeof(Product) }
//...
};
Last, use db to call Query method :
var query = Db.Query(TableTypeDictionary[queryParams.Table]).Select($"new ({string.Join(",", queryParams.Columns)})", "T", StringComparison.OrdinalIgnoreCase);
You can also bring "Namespace.MyTable"
in the Query method. At this time, you need to rewrite the Query method to another writing method, please refer to this.