I am trying to compare only date part of DateTimeOffset in Linq. But auto generated query still add timezone. I am using DbFuncation.TruncateTime but it is only truncate time part. Timezone part is still comparing. May I know how can I compare DateTimeOffset's DateTime part only.
query.Where(p =>
DbFunctions.TruncateTime(p.ETD) >= trimCriteriaDto.StartDate
&& DbFunctions.TruncateTime(p.ETD) <= trimCriteriaDto.EndDate);
Related
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:
&& 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?
Dates have no format, they're binary types in all databases (except SQLite). SQL Server has date, datetime2, datetimeoffset, time and the legacy datetime for storing dates and time-of-day. Storing dates as strings in a string field is a critical bug that must be fixed. There's no way to control what goes into a string field, which means it's quite easy for garbage or strings with the wrong format to end up in the database.
Trying to parse such strings will result in bad performance and increased blocking even if indexes are used. Indexes are built using the stored values, not function results. Trying to parse PolicyEnd and filter by a specific date would have to scan the entire table, parse the values and only then decide which values to include. It will take Shared locks on the entire table while doing so, which would block any UPDATE or DELETE calls that tried to run at the same time, even if they were outside the date range.
If the field uses a date type, the PolicyEnd property should be a DateTime. In that casefiltering to find all dates after 2022 would be just :
var fromDate=new DateTime(2023,1,1);
var query = ....
where client.Telephone2 == "000000"
&& policy.PolicyEnd >=fromDate
This will result in a parameterized query that can use any indexes covering PolicyEnd to only touch policy rows whose PolicyEnd value matches the criteria.
The JOINs aren't necessary either. It's EF's job to generate the JOINs from the relations between entities. A Client should have a Policies collection. A Policy should have a PolicyType. A LINQ query that returns clients without a second phone whose policies end in the future should be :
var clients=from client in _context.Clients
from policy in client.Policies
where client.Telephone2 == "000000"
&& policy.PolicyEnd >=fromDate
select ...;
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
or since you are checking only year you can try to use the whole data, sometimes it works
var dt = new DateTime(2021, 12, 31).AddDays(1).AddTicks(-1);
...
&& policy.PolicyEnd > dt
My goal is to query the database for entries of the current day. Let's say the user saves a row with a time of '2021-01-27 01:00' and one with '2021-01-27 00:59'. The time zone is GMT+1 so it will be stored in the database in UTC like this:
row1: '2021-01-27T 00:00Z'
row2: '2021-01-26T 23:59Z'
How can I query for rows of the 27th of January 2021 (selectedUtcDate), from the view of the client / client?
The following will only return one entry:
.Where(row => row.Date == selectedUtcDate)
Do I have to use a range to get all entries of the same date?
.Where(row => row.Date >= selectedUtcDate && row.Date < selectedUtcDate.AddDays(1))
Or is this even automatically resolved by entity framework?
This has nothing to do with a database. The problem is, that the 24 hours or January 27th in Beijing are not the same 24 hours in Greenwich.
Internally, you use UTC. If somewhere on a computer in Beijing a date in local time is known, you know the start DateTime of that day and the start DateTime of the next day. After that you can convert these DateTime value to UTC:
DateTime localDay = FetchDateInLocalTime(); // The day in Beijing
DateTime utcDayStartTime = localDay.Date.ToUniversalTime;
DateTime utcNextDayStartTime = utcDayStartTime.AddDays(+1);
Now comes the database part:
var result = dbContext.Orders.Where(order => utcDayStartTime <= order.Date
&& order.Date < utNextDayStartTime);
Simple comme bonjour!
So to answer the original question with help of the comments:
Yes you have to use a range to query dates like this.
And of course you need to use the client's local date converted to utc (or the offset) as Harald Coppoolse mentioned.
(I am using LINQ to SQL for retrieving the table from database)
I need to loop through a Database table(the has a field Data) to mach the current date with the date in table.How can i achieve this?
Don't use a loop - this will be extremely slow if the table is large. You want to do this in a set based fashion - the IQueryable .Where() method, i.e:
MyTable.Where(x => x.SomeDate == DateTime.Today);
This assumes the dates in the DB store the date part only. If the time part is stored in the DB and you want to ignore that in the comparison, you need to do something like:
MyTable.Where(x => x.SomeDate >= DateTime.Today && x.SomeDate < DateTime.Today.AddDays(1));
I have a simple LINQ query. I would like to only check the DateDisable if there is an entry in the database. If the user doesn't select a date to disable the entry will always show. Can someone please show me how to add a conditional statement within linq
return (from promo in context.Promoes
where promo.DateEnable <= DateTime.Today
where promo.DateDisable >= DateTime.Today
orderby promo.SortOrder
select promo).ToList();
Given that DateEnable is a DateTime?, you can do the following:
// Get today.
DateTime today = DateTime.Today;
return (
from promo in context.Promoes
where
promo.DateEnable <= today &&
(promo.DateDisable == null || promo.DateDisable >= today)
orderby promo.SortOrder
select promo
).ToList();
Basically, you need to check for null or whether or not the date is greater than today.
Also you should capture the value outside of the statement, it's not guaranteed that the the LINQ provider will translate DateTime.Today on the database side correctly.
However, be warned that because of deferred execution, if you wait a long time to execute the query, today might not give you the value you expect (if the time between declaring the query and executing it rolls past midnight).
Of course, if your database server is in a different timezone than your application server, then you'll need to ensure that DateTime.Today is handled by your LINQ provider correctly (so that it's executed on the server) and use that if you want to compare against time on the DB server. If your provider doesn't handle translating DateTime.Today correctly, then you'll have to resort to a stored procedure and call that.
var islemList = (from isl in entities.Islemler where (isl.KayitTarihi.Date >= dbas && isl.KayitTarihi.Value.Date <= dbit) select isl);
It gives error: date is not supported in LINQ to Entities...
How can i get date in linq.
Use EntityFunctions.TruncateTime.
if KayitTarihi is a date column in DB (and dbas and dbit are DateTime), use:
var islemList = (from isl in entities.Islemler where (isl.KayitTarihi >= dbas && isl.KayitTarihi <= dbit) select isl);
The .Date property is not supported in Linq to Entities (though it may be supported in other implementations of Linq).
I realize that you only want to compare the dates, but there is no real problem with comparing the datetimes if the dbas and dbit values are datetimes with time 00:00:00.
You might have to offset the dates or use other inequality checks to get the proper interval but the comparison will work as you intend.
I would personally go with Jandek's solution.