1

I want to get entity from string. Actually I don't know if I'm using correct word for that but if I give you an example probably you will understand what I meant.

For instance, you have blog context and Members, Post, Comments etc models (classes). And client will send you name of the class as a string. But in code behind you need to convert that string to actual class so you can use ef queries to filter.

db.Post.ToList() or db.Post.Where(c => c.Title == "xxx"); 

But this "Post" is string. So I need to convert it.

Also some people use switch case style functions but I want to write a generic one. So I don't have to change code even if I add or remove tables.

I'm using this code to get dbset but I can't use any query of it.

var type = Assembly.GetExecutingAssembly()
          .GetTypes()
          .FirstOrDefault(t => t.Name == name);

return dbSet = context.Set(type);
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
Kadir
  • 3,094
  • 4
  • 37
  • 57
  • I think you mean something like this here: http://stackoverflow.com/a/4876732/1685167 – Tyress Dec 14 '15 at 10:12
  • why can't you query over the [`DbSet`](https://msdn.microsoft.com/en-us/library/gg696460(v=vs.113).aspx)?. According to documentation it returns an `IQueryable` object – Santiago Hernández Dec 14 '15 at 10:17
  • 1
    I wound strongly recommend not to do it that way, and solve your problem with routing or some other way, that does not involve reflection. Otherwise you will have lots of problems with maintaining the solution. – Red Dec 14 '15 at 10:17
  • @Tyress thanks for that, actually it solves my another question but it's not solving this question. – Kadir Dec 14 '15 at 12:22
  • @SantiagoHernández I can't reach the class members when I use the code that I gave in question and it's just using ToListAsync() method and than I can use query but first one gave me all database rows which can be millions of rows. Also I could not cast dbset to dbset. – Kadir Dec 14 '15 at 12:22
  • may be this help https://stackoverflow.com/questions/48041821/dynamically-access-table-in-ef-core-2-0?noredirect=1&lq=1 – M.Ali El-Sayed May 20 '18 at 21:30
  • Thanks @M.AliEl-Sayed but this is for .net core. If I migrate to .net core I will definately use it. Thanks for link. – Kadir May 21 '18 at 14:01

0 Answers0