加入3表 [英] Join 3 table
问题描述
我想通过LINQ加入3表,我这样做了:
var results = northwind.Products.Join(northwind.Categories,c => c.CategoryID,d => d.CategoryID ,(c,d)=> new {c.ProductID,c.ProductName,c.SupplierID,d.CategoryName})
.Where(q => q.ProductID> 12)
。 (northwind.Suppliers,f => f.SupplierID,g => g.SupplierID,(f,g)
=> new {f.CategoryName,f.ProductName,g.CompanyName,g.ContactName, g.Country});
但查询太长了,谁能告诉我写得更短?
谢谢。
这是一种不同的编写方式,它更简洁,但最终两种方式在后端产生相同的SQL。
SELECT [t2]。[CategoryName],[t0]。[ProductName],[t1]。[CompanyName],[t1 ]。[ContactName],[t1]。[Country]
FROM [dbo]。[Products] AS [t0]
INNER JOIN [dbo]。[供应商] AS [t1] ON [t0]。[SupplierID] =([t1]。[SupplierID])
INNER JOIN [dbo]。[Categories] AS [t2] ON [t0]。[CategoryID] =([t2]。[CategoryID])
WHERE [t0]。[ProductID]> 12
qresult = from p in db .Products
var
其中 p.ProductID> ; 12
join s in db.Suppliers on p.SupplierID equals s.SupplierID
join c in db.Categories on p.CategoryID equals c.CategoryID
选择 new {c.CategoryName,p.ProductName,s.CompanyName,s.ContactName,s.Country};
I want to join 3 table by LINQ , i did this :
var results = northwind.Products.Join(northwind.Categories, c => c.CategoryID, d => d.CategoryID, (c, d) => new { c.ProductID, c.ProductName, c.SupplierID, d.CategoryName })
.Where(q => q.ProductID > 12)
.Join(northwind.Suppliers, f => f.SupplierID, g => g.SupplierID, (f, g)
=> new { f.CategoryName, f.ProductName, g.CompanyName, g.ContactName, g.Country });
but the query is too long, who can tell me to write it shorter ?
thank.
This is a different way to write it which is a little cleaner, but in the end both ways produce the same exact SQL on the back end.
SELECT [t2].[CategoryName], [t0].[ProductName], [t1].[CompanyName], [t1].[ContactName], [t1].[Country]
FROM [dbo].[Products] AS [t0]
INNER JOIN [dbo].[Suppliers] AS [t1] ON [t0].[SupplierID] = ([t1].[SupplierID])
INNER JOIN [dbo].[Categories] AS [t2] ON [t0].[CategoryID] = ([t2].[CategoryID])
WHERE [t0].[ProductID] > 12
qresult = from p in db.Products where p.ProductID > 12 join s in db.Suppliers on p.SupplierID equals s.SupplierID join c in db.Categories on p.CategoryID equals c.CategoryID select new {c.CategoryName, p.ProductName, s.CompanyName, s.ContactName, s.Country };
var
这篇关于加入3表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!