Use LINQ Lambda expressions to perform multi-table joins
LINQ allows joining multiple tables using lambda expressions. Let's say we have three classes:
<code>Product { Id, ProdName, ProdQty } Category { Id, CatName } ProductCategory { ProdId, CatId }</code>
Concatenation using Lambda expressions
These tables can be joined using the following code:
<code>var query = product.Join( productcategory, p => p.Id, pc => pc.ProdID, (p, pc) => new { product = p, productcategory = pc } ).Join( category, ppc => ppc.productcategory.CatId, c => c.Id, (ppc, c) => new { productproductcategory = ppc, category = c } );</code>
This will generate objects of the following classes:
<code>QueryClass { productproductcategory, category }</code>
Populate new object
To populate a new object with the connection result properties, you can use the following Select method:
<code>var categorizedProducts = query.Select(m => new { ProdId = ???, CatId = ???, // 其他赋值 });</code>
Get attribute value
The specific property to be assigned can be obtained from the connected object as follows:
<code>ProdId = m.ppc.p.Id, // 或 m.ppc.pc.ProdId CatId = m.c.CatId // 其他赋值</code>
Query syntax alternatives
Alternatively, you can use query syntax, which provides a more concise approach:
<code>var categorizedProducts = from p in product join pc in productcategory on p.Id equals pc.ProdId join c in category on pc.CatId equals c.Id select new { ProdId = p.Id, // 或 pc.ProdId CatId = c.CatId // 其他赋值 };</code>
The results of this query are the same as the lambda expression method. If readability is more important, it is recommended to use query syntax.
The above is the detailed content of How to Perform Multiple Table Joins Using LINQ Lambda Expressions?. For more information, please follow other related articles on the PHP Chinese website!