Reputation: 2407
I have a User
class that has a GetQueryable
method. Another method, Select()
, calls GetQueryable()
. I want to use the Select
method without passing the type User
to the Select
method, because I have it in this but I can't use it.
Type type =
this.GetType();
???
var x = this.GetQueryable<
???>().ToList();
class Program
{
static void Main(string[] args)
{
var acc = new User();
acc.Select();
}
}
public partial class User
{
public DB_Test001Entities context;
public User()
{
context = new DB_Test001Entities();
}
public void Select()
{
Type type = this.GetType();
var x = this.GetQueryable< **???** >().ToList();
}
public IQueryable<TEntity> GetQueryable<TEntity>(List<string> includes = null) where TEntity : class
{
IQueryable<TEntity> items = context.Set<TEntity>();
if (includes != null && includes.Any())
includes.Where(i => i != null).ToList().ForEach(i => { items = items.Include(i); });
return items;
}
}
Upvotes: 0
Views: 1612
Reputation: 1565
You can do it using reflection. The following sample works smoothly. In program you can use Clerk
or Manager
, just any instance derived from User
to call Select
. You can improve your program with this.
class Clerk : User { }
class Manager : User { }
internal class User
{
public User() { }
public string Name { get; set; }
public void Select()
{
var list = new List<string>() {"Jack", "Martin"};
Type thisType = GetType();
MethodInfo method = thisType.GetMethod("GetQueryable").MakeGenericMethod(thisType);
method.Invoke(this, new object[] {list});
}
public IQueryable<TEntity> GetQueryable<TEntity>(List<string> includes = null) where TEntity : User, new()
{
if(includes != null)
{
Console.WriteLine(typeof(TEntity));
var entity = new List<TEntity>(includes.Count);
entity.AddRange(includes.Select(item => new TEntity {Name = item}));
return entity.AsQueryable();
}
return null;
}
}
class Program
{
static void Main()
{
User usr = new Manager();
usr.Select();
}
}
Upvotes: 3