0

I want to db.Set to query different tables dynamically. I have many entity models such as User, Invoice, Address or Product classes. How can I parse string "User" to become a class then db.Set? which can be set dynamically.

I have tried:

if (s=="User")
  db.Set<User>...
else if (s=="Invoice")
  db.Set<Invoice>...

.. above and so on...

Any solutions that make it simple as db.Set< s >? It means "s" can directly string to its Class.

starball
  • 20,030
  • 7
  • 43
  • 238
Andy
  • 13
  • 4
  • Would be possible with reflection, but think about it: what would you do with such a construct? As the compiler does not know the type, you cannot access any of its members (except again using reflection). – Klaus Gütter Jan 01 '23 at 08:09
  • Yes, seems reflection, but the question is how to code to parse string "User" to become a class not a class's instance! – Andy Jan 01 '23 at 08:15
  • [Type.GetType()](https://learn.microsoft.com/en-us/dotnet/api/system.type.gettype) helps you get the `Type` object. Then you can construct the generic type `DbSet` from it using `Type.MakeGenericType()`. But again: what do you want to accomplish? – Klaus Gütter Jan 01 '23 at 08:22
  • The purpose is to parse string to reflect a class, and use in db.Set, otherwise i need to if.. else if.. else if.. to check string. – Andy Jan 01 '23 at 09:34

0 Answers0