如何构建以下动态LINQ to Entities WHERE子句?

时间:2013-06-26 17:34:10

标签: c# linq-to-entities

我需要在LINQ to Entities中模仿这个:

WHERE 
(title = 'title1' AND episodetitle = 'episodetitle1')
OR
(title = 'title2' AND episodetitle = 'episodetitle2')

我试过了:

if (title1 != null && episodeTitle1 != null)
{
      query = query.Where(s => s.Title.Contains(title1)).Where(z => z.EpisodeTitle.Contains(episodeTitle1));
}

if (title2 != null && episodeTitle2 != null)
{
      query = query.Where(s => s.Title.Contains(title2)).Where(z => z.EpisodeTitle.Contains(episodeTitle2));
}

但它给了我这个:

([Extent1].[Title] LIKE @p__linq__0 ESCAPE '~') AND ([Extent1].[EpisodeTitle] LIKE @p__linq__1 ESCAPE '~') 
**AND**
 ([Extent1].[Title] LIKE @p__linq__2 ESCAPE '~') AND ([Extent1].[EpisodeTitle] LIKE @p__linq__3 ESCAPE '~')}

我需要将上面的 AND 更改为OR。

我将如何做到这一点?

1 个答案:

答案 0 :(得分:2)

在一个查询中连接它

query.Where(
s => (
( title1!=null && episodeTitle1!=null && s.Title.Contains(title1) && s.EpisodeTitle.Contains(episodeTitle1) )
||
( title2!=null && episodeTitle2!=null && s .Title.Contains(title2) && s.EpisodeTitle.Contains(episodeTitle2) )