'DbSet variable table name

I am writing an application where I need to abstract the DbSet table name. Instead of calling _db.Activities.ToList() (where Activity is a table in Sql) the code below will work for any variable table input.

Now I wanted to use .Where(),.OrderBy(),.FromSqlRaw() and other methods on top of the existing code.

How can I write _db.Activities.FromSqlRaw(...) for example, with a variable table name, just like it is doing for the GetAll method.

This is my DbSet for Activity

public virtual DbSet<Activity> Activities { get; set; } = null!;

This is the method to get all records from a variable table

public dynamic GetAll(string Table)
        {
            var curEntityPI = _db.GetType().GetProperty(Table);
            var curEntityType = curEntityPI.PropertyType.GetGenericArguments().First();
            // Getting Set<T> method
            var method = _db.GetType().GetMember("Set").Cast<MethodInfo>().Where(x => x.IsGenericMethodDefinition).FirstOrDefault();
            // Making Set<SomeRealCrmObject>() method
            var genericMethod = method.MakeGenericMethod(curEntityType);
            // invoking Setmethod into invokeSet 
            dynamic invokeSet = genericMethod.Invoke(_db, null);
            // invoking ToList method from Set<> invokeSet 
            return Enumerable.ToList(invokeSet); 
        }

The general idea comes from this post

reflection-linq-dbset



Solution 1:[1]

Define return type of method as List< dynamic> instead of dynamic

public List<dynamic> GetAll(string Table)  
{
    //your code...
    return Enumerable.ToList(invokeSet); 
}

Activity Class:

public class Activity
{
    public int Field1 { get; set; }
    public string Field2 { get; set; }
}

So, you can use all methods of List type

var activityList = GetAll("Activities");
var filteredList = activities.Where(x => x.Field1 > 1);
var orderedList = filteredList.OrderBy(x => x.Field2);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iemre