0

I have this function

  public IList<TEntity> GetData<TEntity>() where TEntity : class
    {
        return _DbContext.Set<TEntity>().ToList();
    }

and I call this function like this

GetData<View_Export_Books>()

So now I have to load the class View_Export_Books dynamically from a string. Is this possible?

Thanks for any help.

Add Comment:

I have View_Export_Books as string and i want convert it to a generic parameter.

Dario M.
  • 415
  • 7
  • 21
  • What are you asking exactly? Are you asking for a way to convert a generic parameter to a string? or how to change the method to not use generics and accept a string as a parameter instead? – Sweeper Aug 24 '17 at 09:40
  • 2
    Possible duplicate of [How do I use reflection to call a generic method?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – thehennyy Aug 24 '17 at 09:41
  • I have View_Export_Books as string and i want convert it to a generic parameter. – Dario M. Aug 24 '17 at 09:45

1 Answers1

0

I wish it could help you. Please let me know if you have any question.

    public class MyClass
    {
        public IList<TEntity> GetData<TEntity>() where TEntity : class
        {
            return _DbContext.Set<TEntity>().ToList();
        }

        public void Test()
        {
            var type = GetTypeOf("View_Export_Books");
            var method = typeof(MyClass).GetMethod("GetData").MakeGenericMethod(type);

            //This was a mistake.
            //var instance = Activator.CreateInstance(type);

            method.Invoke(this/*instance*/, new object[]{ });
        }

        private Type GetTypeOf(string className)
        {
            var assembly = AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetTypes().Any(t => t.Name == className));
            return assembly.GetTypes().First(t => t.Name == className);
        }
    }
Hamid Mayeli
  • 805
  • 1
  • 14
  • 24