2014-02-18 32 views
0

所以,經過大量的工作,我發現我有一個問題執行查詢使用LINQ到SQL的其他查詢。請看下面我如何以我喜歡的方式擁有它。當我這樣做時,我得到了一個Object reference not set to an instance of an object錯誤。最後,我有一種感覺,因爲我如何將查詢存儲在變量中。 NotDownloadedIds只是一個過濾表,所以我把它存儲在Iqueryable <tableName>。這樣我可以將它傳遞給一個方法。這是我工作的醜陋的查詢:Linq到SQL,無法分開查詢

var storesLeft = (from x in cDataContext.CategoryCountryCategoryTypeMappings 
join y in cDataContext.Categories 
on x.CategoryID equals y.CategoryID 
where (y.StorefrontID == 73) 
&& !(
    from ndID in 
    (
    from b in cDataContext.CategoryCountryCategoryTypeMappings 
    where 
    !(
    from dll in cDataContext.DownloadLogs 
    where dll.DTS.Hour == DateTime.Now.Hour 

    select dll.CategoryCountryCategoryTypeMappingID) 
    .Contains(b.CategoryCountryCategoryTypeMappingID) 
    select b) 
    select ndID.CategoryCountryCategoryTypeMappingID) 
.Contains(x.CategoryCountryCategoryTypeMappingID) 
select x); 

我想要做的是將其中一些froms分離到其他查詢。是這樣的:

var storesLeft = (from x in cDataContext.CategoryCountryCategoryTypeMappings 
join y in cDataContext.Categories 
on x.CategoryID equals y.CategoryID 
where (y.StorefrontID == 73) && 
!(from ndID in notDownloadedIds 
select ndID.CategoryCountryCategoryTypeMappingID) 
.Contains(x.CategoryCountryCategoryTypeMappingID) 
    select x); 

其中notDownloadedIds樣子:

(from x in cDataContext.CategoryCountryCategoryTypeMappings 
    where !(from dll in cDataContext.DownloadLogs 
    where dll.DTS.Hour == DateTime.Now.Hour 
    select dll.CategoryCountryCategoryTypeMappingID) 
    .Contains(x.CategoryCountryCategoryTypeMappingID) 
    select x); 

爲什麼第一部作品,和其他2沒有什麼想法?有什麼我可以做的,使查詢看起來像第二個2?

編輯:解釋這個查詢在第一個地方做了什麼。 Not downloadedIds獲取行時間戳匹配當前小時的所有cccMappings(categoryCountryCategoryTypeMappings),並且在當前日誌中找不到它的cccMapings。

+0

好吧,那麼你到目前爲止嘗試過什麼?你有哪些麻煩? –

+0

對不起,我做了一個編輯,使我的問題更清晰。我想單獨在第二個代碼塊中顯示查詢,這會使notDownloadedId看起來像它在第三個。但是,這會導致一個空的異常錯誤 –

+0

另外我讓異常更清晰 –

回答

3

你可以肯定地重構查詢,使其更具可讀性,可理解性和簡潔性。您可以e.g取代

(from dll in cDataContext.DownloadLogs 
where dll.DTS.Hour == DateTime.Now.Hour 

select dll.CategoryCountryCategoryTypeMappingID) 
.Contains(b.CategoryCountryCategoryTypeMappingID) 

cDataContext.DownloafLogs.Any(dll => 
    dll.DTS.Hour == DateTime.Now.Hour && 
    dll.CategoryCountryCategoryTypeMappingID == b.CategoryCountryCategoryTypeMappingID 
) 

,因爲它是真的很難理解你正在努力實現與上面的查詢是什麼。

+0

是的,但這是一個小的重構。它有幫助,但我的意思是查詢一個查詢。特別是因爲其他查詢將使用notdownloadedIds。我會在原始文章中添加一個編輯來解釋查詢在做什麼。 –

+0

在某種程度上,這幫助我重新審視我的代碼。在我的困惑中,我搞砸了我想要做的事情。我不知道我甚至在做什麼。我重構,它工作正常,看起來乾淨。 –

+0

格奧爾格,我會從你的第一句話中刪除單詞* more * :) –