如何在Linq中将动态创建的字符串用作WHERE条件

时间:2012-12-22 09:27:25

标签: c# criteria

我要创建返回IQueryable的方法,而tor取决于确切的类型。 是否有可能准备任何可以在WHERE语句之后使用的标准来获得它?

例如if T == License i use "c.fkCustomer == Organization.Customer"

if T== People,我使用"c.fkPeople== Organization.People"等。

XPQuery<T> cQuery = new XPQuery<T>(cSession);
IQueryable CurrQr = from c in cQuery 
                    where "c.fkCustomer == Organization.Customer" 
                    select c;

有人可以提出建议,如何实现这一目标?

2 个答案:

答案 0 :(得分:4)

我认为你最好在这里使用lambda作为参数而不是动态linq例如。

public IQueriable<T> MyQuery<T>(Expression<Func<T, bool>> predicate)
{
    return new XPQuery<T>(cSession).Where(predicate)/*and any other bits you want at the moment this is a straight up where clause so kinda pointless*/;
}

然后你可以用:

来调用它
MyQuery(c=> c.fkCustomer == Organization.Customer)

MyQuery(c=> c.fkPeople == Organization.People)

答案 1 :(得分:1)

是的,这可以做到。一种方法是使用您可以在此处找到的动态查询库以及有关如何使用它的详细信息: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx