1

I have a method that returns records from a dynamically presented table:

public static List<T> Get<T>() where T : class
        {
            using NanoWikiDBContext context = new NanoWikiDBContext();

            return context.Set<T>().AsQueryable().ToList();
        }

And now I need to get records, when there is no type T, by the table name. How to do it?

You can't just pass GetType (), it doesn't work. What is a way to get data through a dynamic object without using generic T directly?

public static List<T> GetByName<T>(string table) where T : class
        {
            using NanoWikiDBContext context = new NanoWikiDBContext();

            var model = Activator.CreateInstance(Type.GetType($"{StringsManager.GetProjectName()}.Models.Database.{table}")).GetType();

            return context.Set<model.GetType()>().AsQueryable().ToList();
        }
Magnetron
  • 7,495
  • 1
  • 25
  • 41
Kanasi
  • 59
  • 2
  • 12
  • What ORM are you using? The Entity Framework? – Paul Sinnema Nov 08 '20 at 17:27
  • @PaulSinnema, not yet, entity core. It's a asp.net core project – Kanasi Nov 08 '20 at 17:33
  • The 'using' is wrong anyway. Should be using(var nanow context = new nanow()){ .. other code here (including the return) }. – Paul Sinnema Nov 08 '20 at 17:53
  • Take a look at the Entity Framework first before doing anything else. And also take a look at the MVVM pattern widely used in applications. – Paul Sinnema Nov 08 '20 at 17:55
  • @PaulSinnema, return is working correctly. Because it's a last C# modificatory of code. Can you help me with this problem? How to using table name or create instance with db context class? – Kanasi Nov 08 '20 at 18:06
  • You can't have/call generic method without passing generic type arguments (or generic argument which allows inferring it). EF Core has nothing to do with that. The best you can get is non generic method returning non generic `IEnumerable` or `IEnumerable`. – Ivan Stoev Nov 08 '20 at 18:08
  • @IvanStoev, I know it. I need to convert my instance to T type and send to Set method. I want to know ways, how to do that, when u don't know with type of table will entered ?! – Kanasi Nov 08 '20 at 18:10
  • 1
    @IvanStoev, the task - return records from the table with dynamic table name. That's all – Kanasi Nov 08 '20 at 18:11
  • I understand, but the question is what is the return **type** of such method and what you can further do with it. I've already answered similar question here https://stackoverflow.com/questions/48041821/dynamically-access-table-in-ef-core-2-0/48042166#48042166, but the result is almost useless - all you can do is to cast it to `IEnumerable` in order to be able to call `ToList()` and that's all. – Ivan Stoev Nov 08 '20 at 18:17

0 Answers0