1

I've this code and everything works just fine.

using (var db = new ApplicationDbContext())
{
    md = db.Modles.ToList();
}

My question is that I have a parameter called M and that is the name of a Model I've created, so it can be dynamic.

Is there a way to do something like this:

var M = "Modles"; // or M = "Modles2"
using (var db = new ApplicationDbContext())
{
    md = db[M].ToList();
}

I've tried Entity Framework Get Table By Name and Entity Framework get table by variable name but without any luck. Can this be done?

nzrytmn
  • 6,193
  • 1
  • 41
  • 38
  • 1
    "*[...] but without any luck*" - what exactly did not work with the proposed answers? – germi Nov 25 '19 at 11:53
  • Do you use .net core , If so have a look FindEntityType method https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.modelextensions.findentitytype?view=efcore-3.0 – nzrytmn Nov 25 '19 at 13:56

1 Answers1

0

The solution on second link you provided actually doesn't work because it's missing a simple step: The method Set on DbContext is a generic method, so you cannot simply invoke it without telling the type, either at compile time or at least at runtime. Since you want it to be called dynamically, runtime resolution is the option you're left with. The following example should work:

var entityNs = "myentities";
var table = "Model";
var entityType = Type.GetType($"{entityNs}.{table}");
var methodInfo = typeof(ApplicationDbContext).GetMethod("Set");
var generic = methodInfo.MakeGenericMethod(entityType);
dynamic dbSet = generic.Invoke(myContext, null);
var list = dbSet.GetList();

Reference: How do I use reflection to call a generic method?

devb
  • 269
  • 1
  • 8
  • `typeof(ApplicationDbContext).GetMethod("Set")` return the error `Ambiguous match found.` – Tony Nielson Nov 26 '19 at 13:22
  • @TonyNielson odd, it doesn't happen to me. Did you perhaps overload the Set method in ApplicationDbContext? Try modifying the line as follows: `var methodInfo = typeof(ApplicationDbContext).GetMethod("Set", new Type[0]);` – devb Nov 27 '19 at 08:04