[FIXED] Using Where clause for DateTime field using a LINQ statement

Issue

I am trying to return records for users based on their telephone numbers as well as a restriction to the PolicyEnd Field (DateTime Format) to return only those that are greater than or equal to 2022. However, I keep on running into several errors:

  1. && DateTime.ParseExact(s: ti0.Outer.Inner.PolicyEnd,format: "yyy-MM-dd",provider: __InvariantCulture_0) > DateTime.Now)' could not be translated.

            var QUERY = from client in _ipacontext.Inclients
                    join policy in _ipacontext.Inpolicies on client.ClientId equals policy.AccountNo
                    join types in _ipacontext.InpolicyTypes on policy.PolicyType equals types.TypeId
                    where client.Telephone2 == "0000000" && DateTime.ParseExact(policy.PolicyEnd, "yyy-MM-dd", CultureInfo.InvariantCulture) > 2022
    

I have also tried this below but in vain :

where client.Telephone2 == "000000"  &&  Convert.ToDateTime(policy.PolicyEnd).Year >=2022

An example of the Date Format is as below:

2022-08-31 00:00:00.000

Any help on other workarounds?


Solution

Since your db table column format datetime, just try to use function

var dt = new DateTime(2022,01,01);
....

 &&    EF.Functions.DateDiffYear(policy.PolicyEnd, dt) >= 0


Answered By - Serge
Answer Checked By - Pedro (sql.easybugfix Volunteer)

Related Posts

Post a Comment