2010-08-31 47 views
0
var query_loc = (from at in db.amenities_types 
        join a in db.amenities on at.id equals a.amenities_type 
        join u in db.unitInfos on a.unit_id equals u.id 
        join l in db.locations on u.locations_id equals l.id 
        join o in db.organizations on l.organization_id equals o.id 
        join ot in db.organization_types on o.id equals ot.organization_id 
        where (((u.price >= low_rent) && (u.price <= high_rent)) 
           || (u.price == null)) 
        && (u.bedrooms <= beds) && (u.bathrooms <= baths) 
        && amenities_list.Contains(at.id) 
        && (((ot.active == true) && (DateTime.Now <= ot.deactivateDate)) 
          || ((ot.active == true) && (ot.deactivateDate == null))) 
         && (((l.active == true) && (DateTime.Now <= l.deactivateDate)) 
          || ((l.active == true) && (l.deactivateDate == null))) 
        && (ot.type == 8) 
        orderby o.name ascending, l.name ascending 
        select new { l, o, u, ot, at }); 

我需要更換的具體線是如何使用LINQ to SQL中的列表創建動態where子句?

其中 amenities_list.Contains(at.id)

相反,它需要產生這樣的SQL([at.id] = 29和[在.id] = 30 AND [at.id] = 40)

那麼如何讓我的List在LINQ to SQL中產生上述SQL代碼。

+1

'([ at.id] = 29 AND [at.id] = 30 AND [at.id] = 40)'總是錯誤的。你的意思是[at.id] IN(29,30,40)'? – 2010-08-31 19:14:37

+0

哎喲,我的頭!這傷害:( – 2010-08-31 19:15:47

+0

是這樣呢? INT []列表= {1,2,3} 然後 其中at.id列表? – MilkyWayJoe 2010-08-31 19:18:25

回答

0

請爲您的子句創建方法,您嚇到我了。

var query_loc = (from at in db.amenities_types 
       join a in db.amenities on at.id equals a.amenities_type 
       join u in db.unitInfos on a.unit_id equals u.id 
       join l in db.locations on u.locations_id equals l.id 
       join o in db.organizations on l.organization_id equals o.id 
       join ot in db.organization_types on o.id equals ot.organization_id 
       where 
        PriceIsValid(u) 
       && BedsAndBathsArevalid(u) 
       && AtIdIsValid(at.id) 
       && SomeCrazyDateConditionIsValid(ot, l) 
       && TheOtTypeIsValid(ot) 
       orderby o.name ascending, l.name ascending 
       select new { l, o, u, ot, at }); 

如果你意味着at.is = 29 OR at.id = 30 OR at.id = 40,然後用等的AtIdIsValid(at.id)謂詞:

bool AtIdIsValid(int atId){ return (atId == 29 || atId == 30 || atId == 40); } 
+0

感謝幫助的人,我仍然習慣於編寫SQL,這個信息有h很高興。 – Caimen 2010-08-31 21:37:06

+0

這是linq-to-sql,這是行不通的。 Linq-to-sql無法將自定義方法轉換爲SQL – jeroenh 2010-08-31 22:30:28

+0

jeroenh是對的,你不能在linq中使用自定義函數。 OP在標記爲答案之前是否讓他的代碼工作? – johnnywhoop 2010-09-01 19:44:52