How to use ToShortDateString in linq lambda expression?

前端 未结 4 1501
眼角桃花
眼角桃花 2020-12-07 01:16

I need to call ToShortDateString in a linq query suing lambda expressions:

toRet.Notification = Repositories
    .portalDb.portal_notifications.OrderByDescen         


        
相关标签:
4条回答
  • 2020-12-07 01:45

    ToShortDateString() method usually used to work only with date and ignore time stamps.

    You will get exactly today result-set by using the following query.

    Repositories.portalDb.portal_notifications.OrderByDescending(p =>       p.id)
            .FirstOrDefault(p => p.date.Date == DateTime.Now.Date);
    

    By using Date property of DateTime struct you can just fetch record of that date only.

    Note: Linq to Objects. Only works if you CAN (or have option) to bypass ToShortDateString() method

    0 讨论(0)
  • 2020-12-07 01:49

    Linq to Entities cannot convert ToSortDateString method into SQL code. You can't call it on server side. Either move filtering to client side (that will transfer all data from server to client), or consider to use server-side functions to take date part of date (you should pass DateTime object instead of shortDateString):

    EntityFunctions.TruncateTime(p.date) == dateWithoutTime
    
    0 讨论(0)
  • 2020-12-07 01:51

    Try this,

    You can also used with below code.

    Activity = String.Format("{0} {1}", String.Format("{0:dd-MMM-yyyy}", s.SLIDESHEETDATE), String.Format("{0:HH:mm}", s.ENDDATETIME))
    
    0 讨论(0)
  • 2020-12-07 02:05

    You shouldn't be forcing a string comparison when what you're working with is Date/time data - as soon as you force string comparisons, you're suddenly having to deal with how the strings are formatted.

    Instead, have something like:

    var endDate = targetDate.AddDays(1);
    
    toRet.Notification = Repositories
    .portalDb.portal_notifications.OrderByDescending(p =>       p.id)
    .FirstOrDefault(p => p.date >= targetDate && p.date < endDate);
    

    (Assuming that targetDate is whatever DateTime variable you had that was used to produce shortDateString in your code, and is already a DateTime with no time value)

    0 讨论(0)
提交回复
热议问题