有没有办法在LINQ查询中包含CASE或条件语句?我试图根据传递给方法的参数动态构建我的select语句。
以下是我在T SQL中编写的方法:
select * from Table1
where Table1Id =
CASE WHEN LEN myParameter > 0
THEN myParamter
ELSE Table1.Table1Id
这是我的Linq查询,SQL CASE推进:
var query = from a in Table1
where a.Table1Id==
CASE WHEN LEN myParameter > 0
THEN myParamter
ELSE Table1.Table1Id
&& a.shortName == myParameter2
&& a.Country == myParameter3
select a;
return query.ToList();
这种事......
看起来我可以使用myParameter.Length()
方法,但不知道从哪里开始使用语法?
好的,这就是整个原始的SQL Statement方法:
string nativeSQLQuery = string.Format("SELECT c.ArticleId ,
+ "c.ArticleTitle,"
+ c.Version,
+ "c.shortName,c.Country,c.ArticleHeader,c.ArticleBody,"
+ "c.DateCreated,c.UserCreated,c.DateUpdated,c.UserUpdated,"
+ "c.isPublished"
+ "c.isBreakingNews"
+ " FROM ISES.vwArticles c "
+ " WHERE c.ArticleTitle = "
+ " CASE WHEN LEN('{1}') > 0"
+ " THEN '{1}'"
+ " ELSE c.ArticleTitle"
+ " END "
+ " AND c.shortName = "
+ " CASE WHEN LEN('{2}') > 0"
+ " THEN '{2}'"
+ " ELSE c.shortName"
+ " END "
+ " AND c.Country = "
+ " CASE WHEN LEN('{3}') > 0"
+ " THEN '{3}'"
+ " ELSE c.Country"
+ " END "
+ " AND c.articleid NOT IN "
+ " (SELECT pa.articleid FROM ISES.tbPublicationArticles pa "
+ " WHERE pa.publicationid={0})", publicationId, ModelSelectedArticleTitle, vRegionShortName, ModelSelectedCountryshortName);
答案 0 :(得分:3)
条件过滤不必是查询本身的一部分,LINQ语句使用延迟加载,因此您可以构建动态查询
var query = someList;
if (myParameter > 0) {
// dynamic filter
query = query.Where(x => x.Table1Id == myParameter);
}
改编为单行
var query = myParameter > 0 ? someList : someList.Where(x => x.Table1Id == myParameter);
重新编写现有代码
var query = _Context.vwArticles
.Where(x => a.ArticleTitle == modelSelectedArticleTitle &&
a.shortName == regionShortName &&
a.Country == modelSelectedCountryshortName);
if (myParameter > 0) {
query = query.Where(x => x.Table1Id == myParameter);
}
return query.ToList();
答案 1 :(得分:-1)
使用条件运算符:
var query = from item in table
let table1Id = myParameter.Length() > 0 ? myParameter : item.Table1Id
select item;