简体   繁体   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();

Your problem is that formatting doesn't belong in the Linq query itself.您的问题是格式不属于 Linq 查询本身。 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.发生这种情况是因为 LINQ to Entities 试图将表达式树转换为 SQL 查询,而 .ToString(string) 无法转换为 SQL。 then make sure you enumerate the collection before doing your formatting.然后确保在进行格式化之前枚举集合。 You can call .ToList(), or you can use range date.您可以调用 .ToList(),也可以使用范围日期。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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