日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Linq to Sql 动态条件另类实现方法

發布時間:2024/4/15 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 动态条件另类实现方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。