EF(Linq)框架使用過程中的小技巧匯總 dbfunctions


這篇博客總結本人在實際項目中遇到的一些關於EF或者Linq的問題,作為以后復習的筆記或者供后來人參考(遇到問題便更新)。

目錄


技巧1: DbFunctions.TruncateTime()的使用

有沒有遇到做這樣的錯誤:

  • LINQ to Entities does not recognize the method 'System.String ToShortDateString()' method, and this method cannot be translated into a store expression.【LINQ to Entities不能識別‘System.String ToShortDateString()’方法】
  • System.NotSupportedException: The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.【LINQ to Entities不支持類型成員‘Date’,僅支持初始化器,實體成員和實體導航屬性】
var query = from order in _orderRepository.GetAll() .Where(o => o.OrderType == OrderType.LineSold) .WhereIf(input.OrderDate!=DateTime.MinValue,o=>o.OrderDate.Date==input.OrderDate.Date) .WhereIf(!string.IsNullOrEmpty(input.OrderNo),o=>o.OrderNo==input.OrderNo||o.OrderNo.EndsWith(input.OrderNo)) .WhereIf(input.Status!=-1,o=>o.Status==input.Status) join device in _deviceRepository.GetAll() .WhereIf(!string.IsNullOrEmpty(input.Code),d=>d.Code==input.Code) on order.TerminalID equals device.Id join trans in _transDetailRepository.GetAll() .WhereIf(!string.IsNullOrEmpty(input.PayOrderNo),t=>t.PayOrderNo==input.PayOrderNo||t.PayOrderNo.EndsWith(input.PayOrderNo)) on order.OrderNo equals trans.OrderNo into leftJoinResults from leftJoinResult in leftJoinResults.DefaultIfEmpty( ) select new LineSoldOrderOutput { Code = device.Code, Id = order.Id, Amount = order.PayFee, OrderDate = order.OrderDate, OrderNo = order.OrderNo, PayOrderNo = leftJoinResult.PayOrderNo??"還沒產生支付方訂單號", Status = order.Status }; 

為啥有這種需求?
因為數據庫中的DateTime類型都是以2016-03-11 11:25:59這種形式保存的,而我在客戶端查詢數據時,只要傳入日期就行,不需要傳入時間部分,所以必須把時間部分咔嚓掉(剪掉)。

正如上面的代碼第三行,一開始是那么寫的,結果報上面的第二種錯誤。
第二次改成了.WhereIf(input.OrderDate!=DateTime.MinValue,o=>o.OrderDate.ToShortDateString()==input.OrderDate.ToShortDateString()),結果報上面的第一種錯誤。

解決辦法

.WhereIf(input.OrderDate!=DateTime.MinValue,o=>DbFunctions.TruncateTime(o.OrderDate)【我用的是EF6,Truncate,翻譯為截斷,該函數顧名思義也就是把時間部分去掉,只保留日期部分】
EF6以前你可能需要用EntityFunctions.TruncateTime(p.date) == dateWithoutTime

其他重點
我上面的代碼還有使用linq進行三張表的連接,更重要的是,前兩張表是內連接,之后再進行左連接。不熟悉linq語法的可以學習一下。

技巧2: Linq中對Datetime字段按照年月分組以及DbFunctions.CreateDateTime()的使用

有時候,在處理數據的時候,需要對數據進行分組,而且是對Datetime類型的字段按照年月進行分組,下面分別使用Linq的方法語法和查詢語法進行分組:

方法語法

dateIncomeDtos = query
    .Where(o => o.OrderDate >= input.Start && o.OrderDate < DbFunctions.AddMonths(input.End,1)) .OrderBy(o => o.OrderDate) .GroupBy(o => DbFunctions.CreateDateTime(o.OrderDate.Year, o.OrderDate.Month, 1, 0, 0, 0)) .Select(group => new DateIncomeDto { Date = group.Key.Value, Income = group.Sum(item => item.PayFee ?? 0) }); 

查詢語法

dateIncomeDtos = from q in query group q by new {date = new DateTime(q.OrderDate.Year, q.OrderDate.Month, 1)} into g select new DateIncomeDto { Date = g.Key.date }; 

方法語法使用的是Linq中提供的DbFunctions類中的CreateDateTime方法,給day的參數傳入一個1至29中的整數,保證每個月中有這一天即可(我這里傳入了1),這樣,在分組的時候,EF就會將數據庫中的每條記錄的OrderDate字段的年和月進行分組。
查詢語法思想是一樣的,只不過用到了匿名類而已。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM