有幾個級別可以做到這一點。您可以使用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
與測試id
和title
的表達式。)
嘗試'where(id!= 0 && e.OwnerID == id)|| t.title == title' –