我需要在关系表上的动态where子句(一对多)在LinqToSql中的帮助。
用户从页面中选择条件。(用户选择子句有4个输入)
,例如CompanyName和CompanyTitle来自Customer表,OrderDate和ShipCity来自Order表.
但是用户可以从页面界面中选择其中的一种,动态查询将在代码隐藏处生成,并从LinqToSql中进行选择。
您可以从其他网页中提供类似类型的示例。

发布于 2009-03-31 14:49:38
您是否正在寻找类似于这样的内容,在其中定义“基本”查询,然后计算参数以确定where子句是否合适?
var result = (from x in context.X
select x);
if(some condition)
{
result = result.AsQueryable().Where(x => x.companyName == name);
}
if(some other condition)
{
result = result.AsQueryable().Where(x => x.companyTitle == title);
}
//return result.ToList();
//return result.FirstOrDefault();
//return result.Count(); //etc我在你的评论中注意到,你提到你的桌子没有一个外键连接?我不知道你怎么会得到一对多的关系,没有某种参照的完整性或关系?
发布于 2009-03-31 05:05:47
取决于您希望它的动态程度--正如其他人已经建议的那样,System.Linq.Dynamic命名空间为在设计时不知道所涉及的实体/成员(表/列)的查询添加了一些简洁的功能。在这种情况下,听起来所涉及的实体和成员已经知道了,您只需要在不同字段之间交替使用where子句条件。这里有一个例子:
from cust in dc.Customer
join ord in dc.Order on cust.CustomerID equals ord.CustomerID
where (companyName == null || cust.CompanyName == companyName)
and (companyTitle == null || cust.CompanyTitle == companyTitle)
and (orderDate == null || ord.OrderDate == orderDate)
and (shipCity == null || ord.ShipCity == shipCity)
select new {cust, ord}发布于 2010-06-23 12:19:50
RobS提供了我认为最有吸引力的解决方案。但是,这是我所使用的方法,但后来我意识到它实际上是完整地执行第一个查询( LINQ到-SQL),然后使用LINQ执行后续的.Where()子句。因此,这不是一个可行的解决方案,因为整个数据集被枚举,然后在内存中过滤掉。
如果我错了,请纠正我--但这是我注意到的。
https://stackoverflow.com/questions/697345
复制相似问题