我的查询在下面给出。如果id = 0我也不希望在我的where子句中,如果title为空,那么我需要从where子句中删除它。是否有任何方法可以做到这一点。我是EF的新手我尝试了很多,但仍然没有运气。
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 :(得分: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
引用{ {1}}加入了表格。以下是上述代码生成的SQL示例:
tbl_Title
(这是使用非零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
的表达式。)