是否有一種方法來包含一個CASE或條件語句內的LINQ查詢?我試圖根據傳入該方法的參數動態構建我的select語句。Linq查詢中的CASE或IF語句?
這裏是我如何寫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語句的方法:
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);
你們是不是要遷移與「可選」的參數,以LINQ的存儲過程?你不必像@詹姆斯表演那樣做。你可以追加'Where()'子句到你的'Queryable <>'和LINQ to Entities將創建適當的SQL語句 – 2015-01-15 16:22:23