2012-03-30 85 views
1

您好我有FEATURESET標識的數組,我的車表得到了子表作爲FeatureSets 我寫的SQL查詢像LinqToSql子Entiity多和運營商

SELECT [t0].[ID] 
FROM [dbo].[SearchResultView] AS [t0] 
Join [dbo].[VehicleFeatureSet] AS [t1] on t0.ID = t1.VehicleID 
where t1.FeatureSetID = 1 and t1.FeatureSetID= 2 and t1.FeatureSetID= 3 

我試過了。但我不能

var features = Request.QueryString["FeatureSets"].Split(',').ToList().ConvertAll(new Converter<string, int>(StrinToint)); 
IQueryable<SearchResultView> result = db.SearchResultViews.Where(m => m.Active == true); 


      foreach (var featuree in features) 
      { 
       result = result.Where(m => m.VehicleFeatureSets.Any(c => c.FeatureSetID == featuree)); 
      } 

我怎麼可以這樣寫LINQ查詢

+1

正如Mattytommo指出的那樣,您的SQL查詢包含一個始終爲false的謂詞('t1.FeatureSetID = 1和...')。有趣的是,我認爲你的linq完全符合你想要達到的目標,但是生成的SQL當然是不同的。我認爲它包含'EXISTS's,但它應該包含它們。這是假設你想要'SearchResultView'記錄在他們的'VehicleFeatureSet'中有_both_1和_2 _and_3。 – 2012-03-30 19:49:34

回答

1

我轉換我的LINQ查詢到SQL查詢。 其實,我不能寫LINQ查詢此:)幫助

SELECT Vehicle.[ID] 
     ,[Make] 
     ,[Model] 
     ,[Km] 
     ,[RegistrationYear] 
     ,[Price] 
     ,[Currency] 
     ,[AdsStartDate] 
     ,[ThumbPhoto] 
    FROM [SearchResultView] as Vehicle 
left Join VehicleFeatureSet vs on Vehicle.ID=vs.VehicleID where Vehicle.Active = 1 
AND vs.FeatureSetID IN(1,5,7,9) // 1,5,7,9 comes from array 
group by Vehicle.[ID],[Make] 
     ,[Model] 
     ,[Km] 
     ,[RegistrationYear] 
     ,[Price] 
     ,[Currency] 
     ,[AdsStartDate] 
     ,[ThumbPhoto] 
Having Count(vs.FeatureSetID) = 4 // length of my feature array 
// sb = msSql query ,StringBuilder 
// Then I used DataContext.ExecuteQuery() 
db.ExecuteQuery<SearchResultView>(sb.ToString()); 

問題固定的感謝。

1

像這樣的事情?儘管你試圖在FeatureSetId上匹配1,2和3?我保持原樣,但如果這就是你的意思,他們可以改爲OR(||)。

var results = (from r in db.SearchResultViews 
       join v in db.VehicleFeatureSet 
       on r.ID equals v.VehicleID 
       where r.Active 
        && v.FeatureSetID == 1 
        && v.FeatureSetID == 2 
        && v.FeatureSetID == 3 
       select r.ID) 
       .ToList(); 

編輯:好的,我現在已經做的是簡單地改寫你的foreach語句,你可以用下面的替換:

results = features 
    .Aggregate(results, (current, feature) => current 
     .Where(v => v.VehicleFeatureSets 
      .Any(vf => vf.VehicleFeatureSetId == feature)) 
     .ToList()); 
+0

嗨感謝您的回答,但我不能寫這個查詢。我有FeatureSetID數組。有動態值。 – halit 2012-03-31 07:33:05

+0

好吧,檢查我在車輛上使用VehicleFeatureSets屬性的編輯,並使用代碼中定義的功能列表。希望有幫助 – mattytommo 2012-03-31 09:57:29

+0

您好@mattytommo感謝您的幫助。我得到錯誤。 「本地序列不能用於除Contains運算符之外的查詢運算符的LINQ to SQL實現。」它不接受「任何」運營商 – halit 2012-04-02 08:37:13