2012-09-28 63 views
0

我的Linq語句給出了一個錯誤。 現在的問題是,我在使用自定義構建的數據層的項目中,所以我不知道我是否創建了錯誤的Linq語句或數據層無法處理它。Linq中的條件Where語句

所以這裏的語句:

IQueryable<Affiliate> temp; 

Func<RolePersonRole, bool> func; 
if (roleMustBePrimary) 
{ 
    func = role => role.RolePersonRoleIsPrimary.Value == true;  
} 
else 
{ 
    func = role => role.RoleId == role.RoleId; 

} 
temp = (from affiliate in DataFacade.Instance().Tables(SessionTicket).Affiliates() 
     join role in DataFacade.Instance().Tables(SessionTicket).RolePersonRoles().Where(func) on affiliate.PersonId 
      equals role.PersonId 
     where role.RoleId == roleId 
       && affiliate.AffiliateAssuranceLevel == assuranceLevelEnum 
     select affiliate); 

的意思是,如果布爾roleMustBePrimary是真實的,一個WHERE語句應添加,如果它是假的,它不應該被添加(因此role => role.RoleId == role.RoleId)。

我得到的錯誤是:

類型的表達 'System.Collections.Generic.IEnumerable`1 [SkillsNG.Modules.RolePersons.Entities.RolePersonRole]' 不是序列

+1

什t如果你將Where(func)移到where子句中? –

回答

2

正如沃特說,你不需要.Where(),可以更清晰地表達出來:

var temp = 
    from affiliate in DataFacade.Instance().Tables(SessionTicket).Affiliates() 
    join role in 
     from r in DataFacade.Instance().Tables(SessionTicket).RolePersonRoles() 
     where roleMustBePrimary && r.RolePersonRoleIsPrimary.Value 
       || !roleMustBePrimary 
     select r 
    on affiliate.PersonId equals role.PersonId 
    where role.RoleId == roleId 
      && affiliate.AffiliateAssuranceLevel == assuranceLevelEnum 
    select affiliate; 
+0

是的!這個伎倆。 – Michel

+0

雖然有一個問題:'Where(func)'構造是不受支持的構造嗎? – Michel

+0

它被支持,沒有問題,你只是混合'查詢語法'的方式和'流利的電話'的方式來表達查詢。有時你無法避免它,但在這種情況下,這是可能的,所以爲了可讀性,我認爲堅持使用查詢語法更好 – Wasp