My query looks like so:
using (var ctx = new PCLvsCompContext())
{
var brokerId = broker?.Id;
var symbolId = company?.Id;
var result = (from t in ctx.TradeHistoryJoineds
where t.TradeDate >= fromDate
&& t.TradeDate <= toDate
&& (brokerId == null || t.BrokerId == brokerId)
&& (symbolId == null || t.SymbolId == symbolId)
select t).OrderBy(x => x.TradeDate).ThenBy(x => x.BrokerName).ToList();
return result;
}
As an example, I run this query with dates like fromDate March-01-2017 toDate March-31-2017. I then captured the generated sql in SQL profiler that this query produces and ran it in SQL management studio. The output was as expected where for each weekday, each company has some trades. The query is based off of a view which casts all dates to "datetime" so that excel can parse them as dates correctly. However, when I put a breakpoint at "return result" and inspect the dates, all but 2 of the dates are March-1-2017. This is incorrect, the query result in SQL manager shows trades for almost every weekday in March (which is correct).
What is going on here? Why is Linq losing its mind?
Although based on the results I cannot see exactly how you would end up with those results, it is very common that you could be dealing with a DateTime timezone issue. I suspect that perhaps you saved your dates to the database using a DateTime object from say DateTime.Now instead of DateTime.UtcNow. So at that point in time and based on the machine it was called on it would be based on the timezone and datelight savings of that machine.
A DateTime object should not be used as it can relate to the region of the SQL database, the region of the server making this LINQ call and so the two regions could be on different timezones.
Instead you should always use DateTimeOffset.
If you cannot do that for some reason, then double-check your dates toDate and fromDate and do:
var utcToDate = toDate.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
var utcFromDate = toDate.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
Which gives something like this if it was run on 3rd April 2018 at 22:56.
2018-04-03T22:56:57.740Z
You would then also need to make sure when you save any date to the SQL backing store that you do ToUniversalTime() firstly. You can check your SQL tables directly with a normal SQL query and they should be stored in the database as the same UTC string format as above, and then the comparison should be obvious to whether it is valid.
However I would strongly recommend changing all your DateTime calls and gets to DateTimeOffset. The only time to use DateTime in majority of cases is for the final display to a user.
Thank you all for your suggestions. For those who are familiar with linq, EF and views this may seem like a stupid oversight, but I will post my shame for others in case this happens to them since the cause and the resulting behavior are not immediately obviously linked (as can be seen by all the suggestions, none of which actually point to the answer).
When you are querying a view using linq and Entity Framework, you apparently must have a column called 'Id', otherwise Entity Framework can't distinguish any of the rows from one another and simply makes some sort of duplication that I can't quite decipher (all the rows were unique based on their data even without an Id column, so I can't quite figure out why this is necessary).
So by adding an the TradeId with an 'Id' alias to the view, then Entity Framework seemed to return to sanity and map the data as expected.
Related
I am attempting to query a table in SQL using LINQ to entities and add a year to a Date column.
I have tried the following query below:
data = data.Where(x => x.DueDate.Value.AddYears(1) >= DateTime.Now);
When I do this, I get the following error message:
LINQ to Entities does not recognize the method 'System.DateTime AddYears(Int32)' method, and this method cannot be translated into a store expression.
I have done some research and it seems as if most people fix this issue by separating the query out and using a variable they then input into the expression.
I can't do this because I need to add the years to my data lambda expression and can't separate them out.
Is there is a simple way to fix this or is there a way to create a pseudo column that adds a year without actually creating an actual table column? I am trying to avoid having to create an entire new SQL column just for the purpose of adding a year to the date displayed.
Thanks for any help.
You can do the inverse and subtract 1 year from DateTime.Now and use that as the comparison value.
var yearAgo = DateTime.Now.AddYears(-1);
data = data.Where(x => x.DueDate >= yearAgo);
Side notes
The comparison value has a time component but based on the naming of the persisted value DueDate might not have a time component. You can remove the time component by using .Date (DateTime.Now.Date.AddYears(-1);) or .Today instead of .Now (DateTime.Today.AddYears(-1);).
If working in different time zones you will need a more robust solution. I would recommend reading Storing UTC Is Not a Silver Bullet by Jon Skeet.
This is my LINQ for returning the matching record
var staffawards = await _context.StaffAwards.FirstOrDefaultAsync(c => c.StaffID == StaffAwards.StaffID && c.EmpID == StaffAwards.EmpID && c.AwardDate == StaffAwards.AwardDate);
The StaffAwards.AwardDate will be in this format "09/12/2020 12:00:00 AM"
whereas the AwardDate in my table will be like this "2020-12-09 17:16:00.000"
How can i convert the StaffAwards.AwardDate in Sql Server datetime?
AnyHelp would be appreciated.
If your code and your database use Date/DateTime types as they should be, and not strings then you need to understand a few things:
date datatypes don't have a format, only strings created from dates have a format. Whatever format you see in your code/sql query tool is the formatting it has applied when it showed you the date (it had to turn it to a string to display it)
a datetime with a time of midnight is a completely different datetime to one where the time is 17:16, just like a number 1.0 is a completely different number to 1.75352; you will never get a database to return you a record with a time of midnight if you use equals and pass a time of anything other than midnight, just like you will never succeed in getting a record where the age of the person is 1.0 by asking "where age = 1.75352"
Either fix up your parameter so it is midnight, like the db is, or use a parameter range (if the dates in the db will have times other than also)
//if the db date is always midnight
.Where(x => x.DateColumnInDb == datetimeParameter.Date);
//if the db might have times too
.Where(x => x.DateColumnInDb >= datetimeParameter.Date && x.DateColumnInDb < datetimeParameter.Date.AddDays(1));
By using a range, we do not risk asking the database to convert every datetime in the table, every time we want to query. Converting data in a where clause is typically a bad idea because it usually leads to significant performance loss because indexes cannot be used
Also, make sure your .net side datetime and your db time use the same timezone or they will actually be referring to different times
To use a Date with the Database-Format you can use the DbFunctions.
Like this:
var staffawards = await _context.StaffAwards.FirstOrDefaultAsync(c => c.StaffID == StaffAwards.StaffID && c.EmpID == StaffAwards.EmpID && DbFunctions.TruncateTime(DateTime.Parse(c.AwardDate)) == StaffAwards.AwardDate);
Important: For TruncateTime, you have to use a DateTime. You have to convert c.AwardDate to DateTime. DateTime.Parse(c.AwardDate)
Most likely, you have the SQL server installed on a separate machine, which may be due to a different date format.
But there is no need for this conversion, the entity framework will do it automatically for you.
If you just compare date, you can use this code :
var staffawards = await _context.StaffAwards.FirstOrDefaultAsync(c => c.StaffID == StaffAwards.StaffID && c.EmpID == StaffAwards.EmpID && c.AwardDate.Date == StaffAwards.AwardDate.Date);
I have a SQL query that needs to average many datetime values server-side (in SQL Server). For example purposes, let's just consider it's a simple query like this on a table with millions of records:
SELECT
SomeField,
AVG(CAST(ADateTime AS decimal(18,8))) AS NumericRepresentation
FROM MyTable
GROUP BY SomeField
As shown, I can't simply take AVG(ADateTime) because SQL Server isn't happy with doing that, but converting it to a Decimal (and later converting it back to a DateTime) works well enough for me.
The obvious way to do something comparable with EntityFramework is to use .Select(tbl => tbl.ADateTime.Ticks).Average(), but this fails at runtime because DateTime.Ticks doesn't translate through Linq-to-Entities.
How should I best go about this? My main need is to average datetime values in some way. The temporary representation (decimals, ticks, etc) isn't terribly important as long as it can be translated back to a DateTime either in SQL or .NET code. What is important, though, is that the averaging is done in SQL Server (I have some fairly complex calculations with this over many records) and I can somehow have the translated DateTime in .NET (whether the translation happens in SQL Server or in .NET, I don't care).
In pure SQL you can do average on a date field with something like this:
-- the smallest date you could possibly have in your data
DECLARE #MinDate DATE = '1/1/1900'
SELECT
SomeField,
DATEADD(DAY, AVG(DATEDIFF(DAY, #MinDate, ADateTime)), #MinDate) as AvgDateTime
FROM MyTable
GROUP BY SomeField
Not sure yet how to translate this to LINQ :)
UPD: Here is the LINQ code:
private static void Test(IQueryable<SomeClass> data)
{
var minDate = DateTime.MinValue;
var avgMilliseconds = data.Select(x => x.SomeDateField.Subtract(minDate).TotalMilliseconds).Average();
var avgDate = minDate.AddMilliseconds(avgMilliseconds);
Console.WriteLine(avgMilliseconds);
Console.WriteLine(avgDate);
}
EF LINQ expressions can make use of SqlFunctions class to make sure the conversion happens correctly.
DateTime minDate = new DateTime(1900,1,1);
var avg = MyTable.Select(myrow => SQLFunctions.DateDiff("second",myrow.ADateTime,minDate).Average();
DateTime avgDate = minDate.AddSeconds(avg);
Previous answer, should be disregarded:
Use Convert.ToDouble. EntityFramework should be able to translate this LINQ to SQL is able to CONVERT(float,...) as long as your column is actually a DateTime and not DateTime2 or DateTimeOffset, but unfortunately Entity Framework is not able to recognize this construct.
.Select(tbl => Convert.ToDouble(tbl.ADateTime)).Average()
An alternate choice is to do it client side:
.Select(tbl => tbl.ADateTime).ToArray().Select(dt => dt.Ticks).Average()
though clearly that's not preferred if you're averaging millions of rows.
I would like to know if it is possible to convert a DateTime object's timezone in a Linq Query. For example
var seats = await _seat.GetAll()
.Where(
DbFunctions.AddHours( x.StartTime, -1 ) >= x.CreationTime.ToUniversalTime());
In the above code, x.StartTime is in UTC timezone whereas x.Creation time is in local timezone. if I call ToUniversalTime() on x.CreationTime I get an exception.
Is it possible to do the conversion inside the Linq query?
I know it is possible to extract CreationTime before the query and convert it, but it would be great to know the possibility to convert it inside the Linq quert exists.
As #MartinLiversage explained in the columns the best solution would be as follows:
You can easily solve your problem by pulling all the rows to the client side and then perform the filtering using your predicate (putting aside the problems created by using "local time".) However, I assume that you want to filter the records on the database server. EF will have to translate your predicate to corresponding SQL and that limits what you can do in the Where clause. The DbFunctions is a way to declare certain simple computations that EF can translate to SQL but there is no way to perform time zone conversions. SQL Server has no concept of time zones.
And as #Martine mentioned the following could be taken into considertion:
SQL Server 2016 just added time zone support. However, there aren't EF DbFunctions for them yet, AFAIK. Still, probably not a good usage here.
I've a column in my table called Date, and I need to compare this date's WeekOfTheYear with DateTime.Now's WeekOfTheYear,
If I give like this,
var cal = CultureInfo.CurrentCulture.Calendar;
int week = cal.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
I am getting 26 here. The same way, in my Entity Framework, I need to compare this week's data, for this I tried like,
entities.WorkingDays.Where(a =>
cal.GetWeekOfYear(a.DATE,CalendarWeekRule.FirstDay,DayOfWeek.Sunday)
== cal.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay,
DayOfWeek.Sunday)
when I run the query like this, am getting error like,
"LINQ to Entities does not recognize the method 'Int32 GetWeekOfYear
(System.DateTime, System.Globalization.CalendarWeekRule, System.DayOfWeek)'
method, and this method cannot be translated into a store expression."
How can I fetch the data for weekly basis here, can any one help me out here....thanks in advance
Call .ToList() first. Like this:
entities.WorkingDays.ToList().Where(a =>
cal.GetWeekOfYear(a.DATE,CalendarWeekRule.FirstDay,DayOfWeek.Sunday)
== cal.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay,
DayOfWeek.Sunday)
See this post for duplicate issue. Basically, the data needs to be in memory before using your GetWeekOfYear functions.
As noted in the comments, this does bring the whole "WorkingDays" table into memory and therefore fetching more data than needed from the DB. Sometimes this is more preferable to using Stored Procedures and sometimes not, depending on the amount of data and other factors based on your application/database architecture.
You could probably use the day of year and divide it with 7 on both instances, and get a sufficient result?
Date.DayOfYear / 7