免责声明:我使用System.Linq.Expressions中的表达式解决了这个问题,但我仍然在寻找更好/更简单的方法.
考虑以下情况:
var query = from c in db.Customers where (c.ContactFirstName.Contains("BlackListed") || c.ContactLastName.Contains("BlackListed") || c.Address.Contains("BlackListed")) select c;
需要根据列入黑名单的术语检查的列/属性仅在运行时可用.如何生成这个动态where子句?
另一个复杂因素是Queryable集合(上面的db.Customers)被输入到'Customer'基类的Queryable中(比如'Person'),因此不能选择编写c.Address.
@Geoff是最好的选择,只需动态LINQ.
如果你想在运行时使用Lambda构建查询的方式虽然我建议你使用PredicateBuilder(http://www.albahari.com/nutshell/predicatebuilder.aspx)并有类似这样的东西:
Expression> pred = null; //delcare the predicate to start with. Note - I don't know your type so I just used T if(blacklistFirstName){ pred = p => p.ContactFirstName.Contains("Blacklisted"); } if(blacklistLastName){ if(pred == null){ pred = p => p.ContactLastName.Contains("Blacklisted"); //if it doesn't exist just assign it }else{ pred = pred.And(p => p.ContactLastName.Contains("Blacklisted"); //otherwise we add it as an And clause } }
对于要包含的所有列,依此类推.当你到达你的查询时,你只需要这样的东西:
var results = db.Customers.Where(pred).Select(c => c);
我用这个来构建LINQ用于搜索,其中有大约20个不同的选项,它产生了非常好的SQL.
var query = from C in db.Customers select c; if (seachFirstName) query = query.Where(c=>c.ContactFirstname.Contains("Blacklisted")); if (seachLastName) query = query.Where(c=>c.ContactLastname.Contains("Blacklisted")); if (seachAddress) query = query.Where(c=>c.Address.Contains("Blacklisted"));
请注意,它们不是互斥的.