c# - 在linq中使用变量名查询表
问题描述
我想知道是否可以通过在 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;
}
解决方案
你在这里:Scott 向你展示如何使用 Dynamic LINQ
你可以做的事情:
通过使用(导入)System.Linq.Dynamic 命名空间,动态表达式 API 被纳入范围。下面是将动态表达式 API 应用于 LINQ to SQL 数据源的示例。
var query =
db.Customers.
Where("City = @0 and Orders.Count >= @1", "London", 10).
OrderBy("CompanyName").
Select("new(CompanyName as Name, Phone)");
记得试试innerIt和outerIt
如何使用outerIt的一个例子
static void Main(string[] args)
{
var claims = new List<Claim>();
claims.Add(new Claim { Balance = 100, Tags = new List<string> { "Blah", "Blah Blah" } });
claims.Add(new Claim { Balance = 500, Tags = new List<string> { "Dummy Tag", "Dummy tag 1" } });
// tags to be searched for
var tags = new List<string> { "New", "Blah" };
var parameters = new List<object>();
parameters.Add(tags);
var query = claims.AsQueryable().Where("Tags.Any(@0.Contains(outerIt)) AND Balance > 100", parameters.ToArray());
}
public class Claim
{
public decimal? Balance { get; set; }
public List<string> Tags { get; set; }
}
推荐阅读
- reactjs - 如何从对象返回html元素
- angularjs - AngularJS文件上传抛出403 Forbidden - IIS Windows Server
- flutter - 在 Flutter 中让 Row 子节点尽可能宽(父节点的剩余宽度)?
- azure-cognitive-search - 模糊搜索和自定义分析器的 Azure 认知搜索问题
- stanford-nlp - GloVe 嵌入中的奇怪值导致导入错误
- python - M1 Mac - GDAL 错误的架构错误 [Django]
- apache-spark - 如何在 Spark sql 中使用外部应用
- database-performance - Cassandra 单 DC 多节点 - 读取查询缓慢
- r - 对于一列中的指定值,查找另一列中值的变化幅度,对于每个 ID
- sql - 使用数组过滤结果的数据库 SQL 查询