简体   繁体   中英

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();

Your problem is that formatting doesn't belong in the Linq query itself. The query is concerned with data, not presentation. This is happening because LINQ to Entities is trying to convert the expression tree into SQL query and .ToString(string) can not be translated into SQL. then make sure you enumerate the collection before doing your formatting. You can call .ToList(), or you can use range date.

I think the following code can help you

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM