动态linq查询选项

时间:2011-05-03 14:53:21

标签: c# linq linq-to-sql

我有一个表单,我正在序列化为一个看起来像这样的json对象:

Fruit: Apple,
StrawberyParam: "test",
AppleParam: 1,
PeachParam: 3,
Car: Porsche
BugattiParam:3,
PorscheParam: "gas",
ToyotaParam: "go",
AnotherParam: "test1"

基本上,用户选择水果和汽车,参数在其他属性中描述。

我正在考虑编写不同的where子句并将它们连接起来创建一个字符串然后像这样应用.ToList:

StrawberryWhere = ....
AppleWhere = ....
PeachWhere = ....
PorscheWhere = ....
.....

然后写下这个:

MyQuery = fromClause + switch based on Fruit and Car selected
          (ie. AppleWhere + PorscheWhere) + selectClause;
MyQuery.ToList();

这是怎么做的?我正在使用linq-to-sql,我对这个框架不太熟悉,所以感谢你的建议。

2 个答案:

答案 0 :(得分:1)

你不会使用字符串,你会做这样的事情:

Expression<Func<TSource, bool>> appleWhere = x => x.Fruit == Fruits.Apple;
Expression<Func<TSource, bool>> porscheWhere = x => x.Car == Cars.Porsche;
// ...

var result = jsonObjects.Where(appleWhere).Where(porscheWhere).ToList();

答案 1 :(得分:0)