2010-01-07 43 views
2

我有一個linq sql查詢,我必須執行union兩組記錄。 我沒有域的數目相等,因此增加了空所有使用UNION,INTERSECT或EXCEPT操作符組合的查詢必須在其目標列表中具有相同數量的表達式

如我的僞代碼

var Values=(from c in containers 

        some joins 
        select new PValues 

{ 
regionid=r.regionid, 

    roomid=r.roomid, 

    floorid=r.floorid, 

    maxarea=r1.maxarea, 

    minarea=r1.minarea, 

    avgarea=r1.avgarea, 

    maxheight=r1.maxheight, 

    minheight=r1.minheight 

}) 
.union 

(from c in containers 

        some joins 

        select new PValues 

{ regionid=j.regionid, 

    roomid=j.roomid, 

    floorid=j.floorid, 

    maxarea=null, 

    minarea=null, 

    avgarea=null, 

    maxheight=j1.maxheight, 

    minheight=j1.minheight 

}) 

谷歌搜索幾個小時後,我才明白,這是錯誤的3.5框架。

現在我想檢索結果。 如何做到這一點 我試圖制定成兩個單獨的IQueryable

var a= first query 

var b =second query 

ilist result =a.union b 

在相同的錯誤這也導致。

我應該如何預先形成

認爲這

感謝 喝罵

回答

0

在SQL中,這通常意味着你需要轉換的空值作爲第一部分的相應數據類型聯合,所以使他們作爲你需要的類型的默認值,如「」或String.Empty爲字符串值,或0爲整數,等等...

0

按照@GalacticJello提到的施放空值,但也投了第一名將另一個查詢中的空值的查詢參數設置爲該類型的可空版本。例如,如果minarea是十進制,則將其轉換爲小數?你可以通過:new Nullable(i.minarea)來確保它推斷出正確的類型。

它可能推斷兩個查詢的不同匿名簽名。此外,爲了減輕這些問題,讓這些屬性的類和更改查詢:

選擇新{..}

選擇新MyObj中{..}

而且這也將解決它。

3

這很可能是LINQ to SQL已知問題的結果。當列值被引用兩次時,它會從結果集中進行優化(即使您可能需要它來使聯盟排隊)。

最通用的解決辦法是使用讓語句:

var Values=(
    from c in containers 
    some joins 
    //You'll need one let statement for each COLUMN, even if they share a value. 
    let maxAreaValue = null 
    let minAreaValue = null 
    let avgAreaValue = null 
    select new PValues 
    { 
     regionid=j.regionid, 
     roomid=j.roomid, 
     floorid=j.floorid, 
     maxarea=maxAreaValue, 
     minarea=minAreaValue, 
     avgarea=avgAreaValue, 
     maxheight=j1.maxheight, 
     minheight=j1.minheight 
    }); 

的更多信息:
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=355734
http://slodge.blogspot.com/2009/01/linq-to-sql-and-union-all-queries.html
SqlException about UNION, INTERSECT and EXCEPT

+0

這爲我工作。 – andr111 2012-04-23 20:13:39

+0

從我收集的信息來看,這個解決方法停止了.Net 4.0的工作,它現在優化了let語句。你可以做的一件事是對值進行某種操作,以防止它被優化掉。例如,只需將一個數字加上零或串聯一個字符串「」。 – 2014-05-03 21:36:43

相關問題