Entity Framework query table name dynamically based on input parameter

感情迁移 提交于 2019-12-12 20:34:10

问题


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.`



来源:https://stackoverflow.com/questions/33855130/entity-framework-query-table-name-dynamically-based-on-input-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!