2017-01-19 22 views
0

我的查詢如下。如果id = 0我不希望在我的where子句中,如果標題爲空,那麼我需要從where子句中刪除它。是否有任何方法可以做到這一點。我是新來的EF我嘗試了很多,但仍然沒有運氣。如何刪除EF6中過濾器爲空的情況

public dynamic GetData(int id,string title){ 

    var entryPoint = (from ep in dbContext.tbl_EntryPoint 
        join e in dbContext.tbl_Entry on ep.EID equals e.EID 
        join t in dbContext.tbl_Title on e.TID equals t.TID 
        where e.OwnerID == id || t.title==title 
        select new { 
         UID = e.OwnerID, 
         TID = e.TID, 
         Title = t.Title, 
         EID = e.EID 
        }).Take(10); 
} 
+0

嘗試'where(id!= 0 && e.OwnerID == id)|| t.title == title' –

回答

1

有幾個級別可以做到這一點。您可以使用where子句(如where ((e.OwnerID == id) || (id == 0)))將其嵌入到生成的SQL中,或者可以完全按照其他方式完成,併爲不同的where子句變體提供整個LINQ表達式的四個獨立副本。我個人推薦一箇中途辦法:使用單獨的代碼分支基於過濾器來構建不同的IQueryable值,不重複的公用部分:

public dynamic GetData(int id, string title) 
{ 
    var baseQuery = 
     from ep in dbContext.tbl_EntryPoint 
      join e in dbContext.tbl_Entry on ep.EID equals e.EID 
      join t in dbContext.tbl_Title on e.TID equals t.TID 
     select new { e, t }; 

    var filtered = baseQuery; // Implicitly type filtered to match the anonymous type in baseQuery 

    if (id > 0) 
    { 
     if (!string.IsNullOrWhiteSpace(title)) 
      filtered = baseQuery.Where(ep => (ep.e.OwnerID == id) || (ep.t.title == title)); 
     else 
      filtered = baseQuery.Where(ep => ep.e.OwnerID == id); 
    } 
    else 
    { 
     if (!string.IsNullOrWhiteSpace(title)) 
      filtered = baseQuery.Where(ep => ep.t.title == title); 
     else 
      filtered = baseQuery; 
    } 

    var entryPoint = filtered.Select(ep => 
     new 
     { 
      UID = ep.e.OwnerID, 
      TID = ep.e.TID, 
      Title = ep.t.Title, 
      EID = e.EID 
     }).Take(10); 

    ... 
} 

實體框架是足夠聰明,知道的是,在匿名類型構建於baseQuery,ep.e是指tbl_Entry加入表,而ep.t是指tbl_Title加入表。下面是從上面的代碼生成的SQL的一個示例:

SELECT 
    [Limit1].[EID] AS [EID], 
    [Limit1].[OwnerID] AS [OwnerID], 
    [Limit1].[TID] AS [TID], 
    [Limit1].[Title] AS [Title], 
    [Limit1].[EID1] AS [EID1] 
    FROM (SELECT TOP (10) 
     [Extent1].[EID] AS [EID], 
     [Extent2].[EID] AS [EID1], 
     [Extent2].[OwnerID] AS [OwnerID], 
     [Extent2].[TID] AS [TID], 
     [Extent3].[Title] AS [Title] 
     FROM [dbo].[tbl_EntryPoint] AS [Extent1] 
     INNER JOIN [dbo].[tbl_Entry] AS [Extent2] ON [Extent1].[EID] = [Extent2].[EID] 
     INNER JOIN [dbo].[tbl_Title] AS [Extent3] ON [Extent2].[TID] = [Extent3].[TID] 
     WHERE [Extent2].[OwnerID] = @p__linq__0 OR [Extent3].[Title] = @p__linq__1 
    ) AS [Limit1] 

(這可使用非零id和非空title,從而走下第一個if情況下產生的,要求.Where與測試idtitle的表達式。)

相關問題