I am writting 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 ideia comes from this post
https://ift.tt/if9Z0A5
Aucun commentaire:
Enregistrer un commentaire