Linq to Sql 动态条件另类实现方法
其實我也不知道是不是另類的,反正我找了好久園子里和其他資源。
無外乎兩類
1,構造動態表達式的,這個真心繁瑣,我是懶人,不想弄表達式。
2,拼SQL語句,直接執行,這個和ado.net就沒有啥區別了。
我想繼續用Linq,有不想用上面的兩種方法,于是我測試了下面這種方法,結果完全符合預期,看看是怎么寫的吧。
記錄在這里,以備查閱
var result = from s in ct.dbContext.LT_Surveyjoin r in ct.dbContext.LT_Inquiry on s.InquiryCode equals r.InquiryCodejoin ig in ct.dbContext.LM_InquiryGuide on r.GuideNo equals ig.GuideCode into tempfrom tt in temp.DefaultIfEmpty()where((!string.IsNullOrEmpty(notificationDateS) && r.NotificationDate.CompareTo(notificationDateS) >= 0) || string.IsNullOrEmpty(notificationDateS))&& ((!string.IsNullOrEmpty(notificationdateE) && r.NotificationDate.CompareTo(notificationdateE) <= 0) || string.IsNullOrEmpty(notificationdateE))&& (s.ForEarthwork == 0 || s.ForEarthwork == 1)select new{s.ForEarthwork,r.GuideNo,r.NoticeDate};主要看where后面的兩句,notificationDateS,和notificationDateE是一個開始日期和結束日期,在畫面上是動態條件。可以不輸入,或是輸入其中一個,或是兩個都輸入。實現的要點就是這一句(!string.IsNullOrEmpty(notificationDateS) && r.NotificationDate.CompareTo(notificationDateS) >= 0) || string.IsNullOrEmpty(notificationDateS),我只能說linq很智能,他能推測出,如果notificationDateS為空,這一竄就是個恒等于真的表達式,linq會忽略掉這個條件。
看看畫面不同的輸入,生成的sql大家就知道了
notificationDateS:2014/03/03
notificationDateE:空白
SELECT [t0].[ForEarthwork], [t1].[GuideNo], [t1].[NoticeDate] FROM [dbo].[LT_Survey] AS [t0] INNER JOIN [dbo].[LT_Inquiry] AS [t1] ON [t0].[InquiryCode] = ([t1].[InquiryCode]) LEFT OUTER JOIN [dbo].[LM_InquiryGuide] AS [t2] ON [t1].[GuideNo] = [t2].[GuideCode] WHERE ([t1].[NotificationDate] >= @p0) AND (([t0].[ForEarthwork] = @p1) OR ([t0].[ForEarthwork] = @p2))notificationDateS:2014/03/03
notificationDateE:2014/03/13
SELECT [t0].[ForEarthwork], [t1].[GuideNo], [t1].[NoticeDate] FROM [dbo].[LT_Survey] AS [t0] INNER JOIN [dbo].[LT_Inquiry] AS [t1] ON [t0].[InquiryCode] = ([t1].[InquiryCode]) LEFT OUTER JOIN [dbo].[LM_InquiryGuide] AS [t2] ON [t1].[GuideNo] = [t2].[GuideCode] WHERE ([t1].[NotificationDate] >= @p0) AND ([t1].[NotificationDate] <= @p1) AND (([t0].[ForEarthwork] = @p2) OR ([t0].[ForEarthwork] = @p3))notificationDateS:空白
notificationDateE:空白
SELECT [t0].[ForEarthwork], [t1].[GuideNo], [t1].[NoticeDate] FROM [dbo].[LT_Survey] AS [t0] INNER JOIN [dbo].[LT_Inquiry] AS [t1] ON [t0].[InquiryCode] = ([t1].[InquiryCode]) LEFT OUTER JOIN [dbo].[LM_InquiryGuide] AS [t2] ON [t1].[GuideNo] = [t2].[GuideCode] WHERE ([t0].[ForEarthwork] = @p0) OR ([t0].[ForEarthwork] = @p1)完全符合我的要求哦,good!這種方法以前有人用過嗎?不知道各位還有沒有更好的動態sql方法哈,歡迎討論哦。
?
轉載于:https://www.cnblogs.com/xiashengwang/p/3586366.html
總結
以上是生活随笔為你收集整理的Linq to Sql 动态条件另类实现方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android使用ViewPager实现
- 下一篇: 【算法导论】学习笔记——第16章 贪心算