簡體   English   中英

如何在nopcommerce c#中的linq查詢中將日期時間轉換為日期

[英]How to convert datetime to date in linq query in nopcommerce c#

 query = (from s in _studentRepository.Table
     //from a in _attendanceRepository.Table.Where(j => j.StudentId == s.Id && (j.Date == date.Date)).DefaultIfEmpty()
     from a in _attendanceRepository.Table.Where(j => j.StudentId == s.Id).DefaultIfEmpty()
     where s.ClassSectionId == searchClassSectionId && (a.Date == Convert.ToString(date, "DD/MM/YYYY") || a.Date == null)
     select new
     {
         AttendanceTypeId = (a != null ? a.AttendanceTypeId : 0),
             Date = (a != null ? a.Date : default(DateTime)),
             Id = (a != null ? a.Id : 0),
             Student = s
     }).ToList().Select(x => new Attendance()
     {
         Id = x.Id,
         AttendanceTypeId = x.AttendanceTypeId,
         Date = x.Date,
         Student = x.Student
     }).ToList();

您的問題是格式不屬於 Linq 查詢本身。 查詢與數據有關,而不是表示。 發生這種情況是因為 LINQ to Entities 試圖將表達式樹轉換為 SQL 查詢,而 .ToString(string) 無法轉換為 SQL。 然后確保在進行格式化之前枚舉集合。 您可以調用 .ToList(),也可以使用范圍日期。

我認為以下代碼可以幫助您

query = (from s in _studentRepository.Table
                     //from a in _attendanceRepository.Table.Where(j => j.StudentId == s.Id && (j.Date == date.Date)).DefaultIfEmpty()
                 from a in _attendanceRepository.Table.Where(j => j.StudentId == s.Id).DefaultIfEmpty()
                 where s.ClassSectionId == searchClassSectionId && (a.Date >= DateTime.Parse(date.ToString(CultureInfo.InvariantCulture)).Date 
                 && a.Date < DateTime.Parse(date.ToString(CultureInfo.InvariantCulture))
                 .Date.AddDays(1).AddTicks(-1) || a.Date == null)
                 select new
                 {
                     AttendanceTypeId = (a != null ? a.AttendanceTypeId : 0),
                     Date = (a != null ? a.Date : default(DateTime)),
                     Id = (a != null ? a.Id : 0),
                     Student = s
                 }).ToList().Select(x => new Attendance()
                 {
                     Id = x.Id,
                     AttendanceTypeId = x.AttendanceTypeId,
                     Date = x.Date,
                     Student = x.Student
                 }).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM