UTC to local time using Linq to Entities

后端 未结 2 1699
無奈伤痛
無奈伤痛 2021-01-27 03:35

I need to translate a field from UTC to local time in a LINQ to Entities query. But it does not recognize the method \'System.DateTime ToLocalTime\' that I was intended to use.

2条回答
  •  一生所求
    2021-01-27 04:16

    To be able to use functions that don't translate to SQL, you need to materialize the table.

    var materializedRequests = Requests.Where(x => !x.Resolved).ToList(); //Materialize list with a ToList call
    
    materializedRequests
        .Where(x =>
            !materializedRequests.Any(y => 
                y.IncommingDateTime.ToLocalTime().Day == x.IncommingDateTime.ToLocalTime().Day
            )
        )
    

    Then you can use pretty much any functions you want. However, materializing the list is a VERY expensive call. Try to filter the list as much as you can before you materialize it.

提交回复
热议问题