【发布时间】:2018-04-25 09:51:01
【问题描述】:
我想知道是否可以通过在 linq 中使用变量来查询数据库集。
首先我查询我的数据库以获取表名作为字符串,我想将其转换为表名:
public static string getTableName()
{
string tableName = string.Empty;
var department= "Sales";
using (var context = new ALLDBEntities())
{
tableName = (from x in context.PROCESS_MATRIX
where x.AREA.Equals(product)
select x.ENTITY).FirstOrDefault();
}
return tableName;
}
现在我将表名作为字符串,我希望能够使用它来编写 linq 查询,但我不想使用alldbEntities.sales,而是使用table。这是因为我需要编写多个查询来做同样的事情,因为我必须查询不同的表。
有没有办法做到这一点?
public List<sales> GetData(DateTime startDate, DateTime endDate)
{
var table = getTableName();
this.startDate = startDate.AddDays(-1);
this.endDate = endDate.AddDays(1);
using (var alldbEntities = new ALLDBEntities())
{
salesinfo = alldbEntities.sales.Where(f => f.Date >= this.startDate && f.Date <= this.endDate).ToList();
}
return salesinfo;
}
【问题讨论】:
-
i want to be able to use this to write a linq query?LInq 仅指列表和表,而不是数据库本身的表名。 -
仅仅因为您希望某些东西是可变的,并不一定意味着您需要使用
string来做到这一点。您是否愿意接受使源表变量而不使用字符串的解决方案? -
@flater 是的,我对其他解决方案持开放态度,这是我设想的方式,但它不起作用,
标签: c# entity-framework linq