2010-09-27 67 views
3

我正在嘗試針對某些實體(EF4,如果這有什麼區別)構建一個簡單的搜索。傳入我的搜索查詢是一個標準對象列表。該crieteria對象看起來是這樣的:在Linq中追加或子查詢

public class ClaimSearchCirtieria 
{ 
    public Guid? FinancialYear { get; set; } 
    public bool AllClaimants { get; set; } 
    public IList<Guid> ClaimantIds { get; set; } 
    public bool AllExpenseCategories { get; set; } 
    public IList<ExpenseCategoryAndTypeCriteria> EpenseCategoryAndTypes { get; set; } 
} 

而且ExpenseCategoryAndTypeCriteria

public class ExpenseCategoryAndTypeCriteria 
{ 
    public Guid ExpenseCategory { get; set; } 
    public bool AllTypesInCatgeory { get; set; } 
    public IList<Guid> ExpenseTypes { get; set; } 
} 

搜索財政年,申請人需要有一個與查詢,然後我需要的費用類別,費用類型被追加爲OR子查詢。

在本質上我試圖做的事:

select * 
from claims 
where <financial year> AND <Claimants> AND (expense type 1 OR expense type 2 or expense category X) 

到目前爲止,我有這樣的:

public PagedSearchResult<Claim> Search(ClaimSearchCirtieria searchCriteria, int page, int pageSize) 
{ 
    var query = All(); 

    if (searchCriteria.FinancialYear.HasValue) 
    { 
     query = from claim in query 
       where claim.FinancialYearId == searchCriteria.FinancialYear 
       select claim; 
    } 

    if (!searchCriteria.AllClaimants) 
    { 
     query = from claim in query 
       where searchCriteria.ClaimantIds.Contains(claim.ClaimantId) 
       select claim; 
    } 

    if (!searchCriteria.AllExpenseCategories) 
    { 
     foreach (var item in searchCriteria.EpenseCategoryAndTypes) 
     { 
      if (item.AllTypesInCatgeory) 
      { 
       //Just search on the category 
       query = query.Where(claim => 
        (from transaction in claim.ClaimTransactions 
        where item.ExpenseCategory == transaction.ExpenseType.ExpenseCategoryId 
        select transaction).Count() > 0 
       ); 
      } 
      else 
      { 
       //Search for the specified types 
       query = query.Where(claim => 
        (from transaction in claim.ClaimTransactions 
        where item.ExpenseTypes.Contains(transaction.ExpenseTypeId) 
        select transaction).Count() > 0 
       ); 
      } 
     } 
    } 

    return PagedSearchResult<Claim>.Build(query, pageSize, page); 
} 

什麼我目前看到的是,最後一次請求的費用類別是隻有費用類別我獲得結果。另外,看代碼,它看起來像我期望這是建立一系列的AND查詢,而不是所需的OR。

任何指針?

回答