Entity Framework query table name dynamically base

2019-07-13 18:48发布

问题:

I have been working in a project which uses Entity Framework as the ORM data model to connect to the SQL database and retrieve data.

Now the basic query which is used to retrieve data is like this

ProjectDataContext dataContext = new ProjectDataContext();   

var result = (from project in dataContext.Projects
              select project).ToList();

Or in lambda

List<Project> lstprojects = dataContext.Projects.Take(10);

Now I would like to pass the table name dynamically based on some input parameter. How can I achieve that?

The way I am currently doing it is a bit messy.

if(tableName = "A")
{
     List<A> lstOfA = dataContext.A.Take(10);
}
else if(tableName = "B")
{
     List<B> lstOfB = dataContext.B.Take(10);
}

and so on...

My question is if there is a neat and clean way to do this without writing so many if else because I understand it may cause performance issues in future.

Thanks

回答1:

Ok after some trial and error I have been able to do it like this-

var type = Type.GetType("A");
context.Set(type).Load();
var result = context.Set(type).Local.Cast<object>().ToList();

Hope it helps.`