实体框架查询表名称动态地基于输入参数 [英] Entity Framework query table name dynamically based on input parameter
问题描述
我一直在使用Entity Framework作为ORM数据模型连接到SQL数据库并检索数据的项目。
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();
或在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);
}
等等...
我的问题是,如果有一个整洁干净的方法,如果没有写这么多,因为我明白这可能会导致性能问题在未来。
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.
谢谢
推荐答案
在尝试和错误后,我已经能够这样做了 -
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();
希望它有帮助。
这篇关于实体框架查询表名称动态地基于输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!