简体   繁体   中英

dynamic join in linq 0 c#

   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};

I want to perform a search based on the above join. The input param could be

C.ClientID and/or P.ProductName and/or P.ProductType and/or O.ShippingType

How would i build a dynamic search clause?

Well, there's Dynamic LINQ . Here's a nice intro from Scott Gu . With Dynamic LINQ, you can build your conditionals. For example,

Where("ClientId = 12")

Another method:

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};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM