簡體   English   中英

LinqToSql中有多個左外部聯接?

[英]Multiple Left Outer Joins in LinqToSql?

是否可以使用linqtosql完成類似的事情?

select * from table t1
left outer join table2 t2 on t2.foreignKeyID=t1.id
left outer join table3 t3 on t3.foreignKeyID=t1.id

我可以同時使用DataLoad選項或聯接語法來使其工作。 但是問題是無論何時我添加第二個左聯接,即使用MULTIPLE sql語句的linqtosql查詢,而不是在基礎sql中進行第二個左聯接。

因此,類似上面的查詢將導致數十個sql調用,而不是一個帶有2個左聯接的sql調用。

我還有其他選擇嗎? 我可以在數據庫中使用視圖,但是現在我負責從扁平化列表創建層次結構,這是首先使用ORM的原因之一。

注意,T2和T3與T1是1:M關系。 是否有可能使linq有效地查詢這些並返回層次結構?

這是一個類似的問題 了解聯接的組成方式。

例如,下面的Linq to Sql在AdventureWorks上查詢:

AdventureWorksDataContext db = new AdventureWorksDataContext();

var productStuff = from p in db.Products
                   join pl in db.ProductListPriceHistories on p.ProductID equals pl.ProductID into plv
                   from x in plv.DefaultIfEmpty()
                   join pi in db.ProductInventories on p.ProductID equals pi.ProductID into pii
                   from y in pii.DefaultIfEmpty()
                   where p.ProductID == 764
                   select new { p.ProductID, x.StartDate, x.EndDate, x.ListPrice, y.LocationID, y.Quantity };

產生與此SQL查詢相同的SQL(通過Profiler驗證):

SELECT Production.Product.ProductID, 
       Production.ProductListPriceHistory.StartDate,
       Production.ProductListPriceHistory.EndDate,
       Production.ProductListPriceHistory.ListPrice,
       Production.ProductInventory.LocationID,
       Production.ProductInventory.Quantity
FROM Production.Product
LEFT OUTER JOIN Production.ProductListPriceHistory ON Production.Product.ProductID = Production.ProductListPriceHistory.ProductID 
LEFT OUTER JOIN Production.ProductInventory ON Production.Product.ProductID = Production.ProductInventory.ProductID 
WHERE Production.Product.ProductID = 764

父表的主鍵上有多個LEFT JOIN,產生一個生成的SQL查詢。

我認為這可能不是解決您問題的正確方法,因為與您的父實體表之間存在多對一的關系:

select * from table t1 
left outer join table2 t2 on t2.foreignKeyID = t1.id 
left outer join table3 t3 on t3.foreignKeyID = t1.id 

這就像一個有多個孩子和多個車輛的人:

說t1是人

id             str
1              Me

說t2是孩子

PK  foreignKeyID   str
A   1              Boy
B   1              Girl

說t3是車輛

PK  foreignKeyID   str
A   1              Ferrari
B   1              Porsche

您的結果集是:

Me Boy Ferrari
Me Girl Ferrari
Me Boy Porsche
Me Girl Porcshe

我看不到這是多么有用的查詢(即使在SQL中也是如此)。

我認為只要將DefaultIfEmpty()調用放在正確的位置,LINQ to SQL就能轉換您的左外部聯接:

var q = from t1 in table
        join t2 in table2 on t1.id equals t2.foreignKeyID into j2
        from t2 in j2.DefaultIfEmpty()
        join t3 in table3 on t1.id equals t3.foreignKeyID into j3
        from t3 in j3.DefaultIfEmpty()
        select new { t1, t2, t3 };

如果正確設置了FK,則不需要那種可怕的聯接語法。

您可能會寫:

var q = from t1 in dc.table1s
        from t2 in t1.table2s.DefaultIfEmpty()
        from t3 in t1.table3s.DefaultIfEmpty()
        select new { t1, t2, t3 };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM