您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“l(fā)inq動(dòng)態(tài)條件查詢?nèi)绾问褂谩?,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“l(fā)inq動(dòng)態(tài)條件查詢?nèi)绾问褂谩卑?
1,linq動(dòng)態(tài)條件之構(gòu)造表達(dá)式樹
private Expression<Func<Blog, bool>> getCondition()
{
Expression<Func<Blog, bool>> expression = blog => true;
if (!String.IsNullOrEmpty(Request["BlogClassID"]))
{
int blogClassID;
if (Int32.TryParse(Request["BlogClassID"], out blogClassID))
{
Expression<Func<Blog, bool>> e2 = blog =>
blog.BlogClass == null;
var invokedExpr = Expression.Invoke
(e, expression.Parameters.Cast
()); expression = Expression.Lambda<Func<Blog, bool>>
(Expression.And(expression.Body, invokedExpr), expression.Parameters);}
}
return expression;
}
主查詢是這個(gè)樣子:
var result = new DongBlogDataContext().Blogs.Where(getCondition());
因?yàn)楦鶕?jù)SQL追蹤,生成SQL類似:
SELECT [t0].[BlogID], [t0].[ChannelID], [t0].[BlogClassID], [t0].[Title], [t0].[Content], [t0].[Tag], [t0].[CreateDateTime] FROM [dbo].[Blog] AS [t0] WHERE [t0].[BlogClassID] IS NULL
這種方法是實(shí)質(zhì)是合并Lamba表達(dá)式,也就是這三句。
SELECT [t0].[BlogID], [t0].[ChannelID], [t0].[BlogClassID], [t0].[Title], [t0].[Content], [t0].[Tag], [t0].[CreateDateTime] FROM [dbo].[Blog] AS [t0] WHERE [t0].[BlogClassID] IS NULL
如果每個(gè)條件合并都這么寫會(huì)很麻煩,幸好已經(jīng)有人給寫好的輔助類:
using System; using System.Linq; using System.Linq.Expressions; using System.Collections.Generic; public static class PredicateBuilder { public static Expression<Func<T, bool>> True () { return f => true; } public static Expression<Func<T, bool>> False () { return f => false; } public static Expression<Func<T, bool>> Or (this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ()); return Expression.Lambda<Func<T, bool>> (Expression.Or (expr1.Body, invokedExpr), expr1.Parameters); } public static Expression<Func<T, bool>> And (this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ()); return Expression.Lambda<Func<T, bool>> (Expression.And (expr1.Body, invokedExpr), expr1.Parameters); } }
這個(gè)類可以用于Expression<Func
2,linq動(dòng)態(tài)條件之構(gòu)造Query
同***種查詢更好的寫法:
private IQueryable getQuery() { IQueryable query = new DongBlogDataContext().Blogs; if (!String.IsNullOrEmpty(Request["BlogClassID"])) { int blogClassID; if (Int32.TryParse(Request["BlogClassID"], out blogClassID)) query = query.Where(blog => blog.BlogClass == null); } return query.OrderByDescending(blog => blog.CreateDateTime); }
主查詢
var result = getQuery();
生成的SQL和***個(gè)完全相同。
到此,相信大家對“l(fā)inq動(dòng)態(tài)條件查詢?nèi)绾问褂谩庇辛烁畹牧私?,不妨來?shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。