2012-04-11 101 views
2

遇到問題,我希望上次導入的數據顯示失敗。我結束訴諸HQL,因爲我不得不執行兩個查詢任何人都可以看到爲什麼這不起作用(正確)在Linq到NHibernate,它是3.1中的已知錯誤?Get Max row(Linq,NHibernate)

我會寫的SQL。

select JobImport.* from 
JobImportResult 
inner join (
    select Max(JobImportResultId) as JobImportResultId 
    from JobImportResult 
    group by JobImportId 
)as tbl on tbl.JobImportResultId = JobImportResult.JobImportResultId 
inner join JobImport on JobImport.JobImportId = JobImportResult.JobImportId 
where ImportFailureReasonId is not null 

HQL我結束了寫作。

select jir.JobImport from JobImportResult jir where jir.Id in 
(select max(mjir.Id) from JobImportResult mjir group by mjir.JobImport) 
and jir.ImportFailureReason is not null 

LINQ的的作品(但我認爲2000年後行將打破)

var innerQuery = Query<JobImportResult>() 
    .GroupBy(jir=>jir.JobImport) 
    .Select(jir=>jir.Max(jr=>jr.Id)); 

var innerQueryListed = innerQuery.ToList(); 

var resultQuery = Query<JobImportResult>() 
    .Where(jir => innerQueryListed.Contains(jir.Id) && jir.ImportFailureReason != null) 
    .Select(jir => jir.JobImport); 

LINQ的不工作:(

var innerQuery = Query<JobImportResult>() 
.GroupBy(jir=>jir.JobImport) 
.Select(jir=>jir.Max(jr=>jr.Id)); 

var resultQuery = Query<JobImportResult>() 
.Where(jir => innerQuery.Contains(jir.Id) && jir.ImportFailureReason != null) 
.Select(jir => jir.JobImport); 
+0

當你說它在2000行後中斷時,錯誤是什麼? – mattytommo 2012-04-11 07:45:20

+0

FYI http://stackoverflow.com/questions/656167/hitting-the-2100-parameter-limit-sql-server-when-using-contains – Mark 2012-04-11 10:43:34

+0

啊我不知道,我知道包含的是DEVIL上性能雖然嘿嘿:) – mattytommo 2012-04-11 10:49:01

回答

3

您使用的.NET 4 ?如果是這樣,請試試這個:

var innerQuery = Query<JobImportResult>() 
    .GroupBy(jir=>jir.JobImport) 
    .Select(jir=>jir.Max(jr=>jr.Id)) 
    .ToList(); 

var resultQuery = Query<JobImportResult>() 
    .Where(jir => innerQuery.Any(j => j == jir.Id) 
     && jir.ImportFailureReason != null) 
    .Select(jir => jir.JobImport) 
    .ToList(); //only use this if you want to resolve the query 

或.NET 3.5 ch ange resultQuery部分爲:

var resultQuery = Query<JobImportResult>() 
    .Where(jir => innerQuery.Count(j => j == jir.Id) > 0 
     && jir.ImportFailureReason != null) 
    .Select(jir => jir.JobImport) 
    .ToList(); //only use this if you want to resolve the query 
+0

我使用.net 3.5。和解決方案的工作原理!!! .net 4解決方案看起來像它也會有2000個結果限制並執行兩個查詢 – Mark 2012-04-11 10:11:50

+0

你能解釋爲什麼innerQuery.Count能夠工作,但我原來的查詢不能嗎?(這是一個在NH後期版本中修復的bug /功能) – Mark 2012-04-11 10:13:31

+0

啊,很高興它可以工作。我認爲你原來的查詢不起作用,因爲你在做ToList之前做了一個Contains,而NHibernate在Queryable上執行Contains時遇到了問題。我在NHibernate中看到了一些使用東西時拋出NotSupportedException的例子像IsNullOrWhiteSpace和類似的東西,bes要做的事情(直到他們修復它)首先解析查詢(使用ToList)然後執行你在原始查詢中無法實現的邏輯。 – mattytommo 2012-04-11 10:22:44