linq 0 c中的动态连接

时间:2009-08-11 23:41:45

标签: c# linq

   var query = from C in db.clients
    join O in db.orders on c.clientid equals O.clientid
    join P in db.products on O.productid equals P.productid
    select new {C,O};

我想根据上述联接进行搜索。输入参数可以是

C.ClientID和/或P.ProductName和/或P.ProductType和/或O.ShippingType

我如何构建动态搜索子句?

2 个答案:

答案 0 :(得分:2)

嗯,有Dynamic LINQ。这是a nice intro from Scott Gu。使用Dynamic LINQ,您可以构建条件。例如,

Where("ClientId = 12")

答案 1 :(得分:0)

另一种方法:

Expression<Func<Client, bool>> clientWhere = c => true;
Expression<Func<Order, bool>> orderWhere = o => true;
Expression<Func<Product, bool>> productWhere = p => true;

if (filterByClient)
{
    clientWhere = c => c.ClientID == searchForClientID;
}

if (filterByProductName)
{
    productName = p => p.ProductName == searchForProductNameString;
}

// other filter cases

var query = from C in db.clients.Where(clientWhere)
    join O in db.orders.Where(orderWhere) on c.clientid equals O.clientid
    join P in db.products.Where(productWhere) on O.productid equals P.productid
    select new {C,O};