简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM