0

I'm trying to build a dynamic filter, where the user can search for columns in tables. To that I'm trying to use System.Linq.Dynamic.Core

var data = Db.MyTable1.Select($"new ({string.Join(", ", queryParams.Columns)})", "T", StringComparison.OrdinalIgnoreCase);

But now I also would like to get the table from the parameter string, something like

var query = Db.Get(queryParams.Table);
query = query.Select...

Working with EntityFrameworkCore 3.1, is there a way to achieve this?

Pablo
  • 1,953
  • 4
  • 28
  • 57

1 Answers1

0

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.

LouraQ
  • 6,443
  • 2
  • 6
  • 16