Linq DateTime comparison not working - linq

I have the following code:
DateTime timeStamp = Convert.ToDateTime(Request.QueryString["TimeStamp"]);
var result = (from rs in db.VRec
where
rs.TimeStamp == timeStamp &&
rs.Fixure == wFixture
select rs).ToList();
The result shows 0 even though the correct timeStamp is passed.
If I remove the part where I do the TimeStamp comparison:
rs.TimeStamp == timeStamp
The code works fine.
Any idea on why the datetime comparison may not be working?

DateTime has a pretty fine resolution - likely you are comparing timestamps that only differ in milliseconds, which will fail. You probably want something like:
DateTime now = DateTime.Now;
DateTime then = now.Add(TimeSpan.FromMilliseconds(1));
const int EPSILON_MS = 10;
if(now.Subtract(then).TotalMilliseconds < EPSILON_MS)
{
Console.WriteLine("More or less equal!");
}

Linq converts DateTime arguments to DateTime2 in the sql query executed.
That is, when you do the comparison the actual sql executed will compare a DateTime to a DateTime2. This comparison will "cast" the DateTime to a DateTime2 and the millisecond part will be expanded to a greater resolution (in an odd way in my opinion, please enlighten me).
Try to execute the following sql:
declare #d1 datetime = '2016-08-24 06:53:01.383'
declare #d2 datetime2 = '2016-08-24 06:53:01.383'
declare #d3 datetime2 = #d1
select #d1 as 'd1', #d2 'd2', #d3 'converted'
select (case when (#d1 = #d2) then 'True' else 'False' end) as 'Equal',
(case when (#d1 > #d2) then 'True' else 'False' end) as 'd1 greatest'

From the question, I do not know if you want to compare the date with time or only the date part. If you only want to compare date then following would work
var result = (from rs in db.VRec
where
rs.TimeStamp.Date == timeStamp.Date &&
rs.Fixure == wFixture
select rs).ToList();
Since you are using some reference to db, it gives me a feeling that you are fetching your records from database (which ORM you are using is not obvious from the question or tags). Assuming that you are using Entity framework the above query will fail with exception that .Date has no direct translation to sql. If so you can rewrite the query as following to make it work.
var result = (from rs in db.VRec
where
rs.TimeStamp.Day == timeStamp.Day &&
rs.TimeStamp.Month == timeStamp.Month &&
rs.TimeStamp.Year == timeStamp.Year &&
rs.Fixure == wFixture
select rs).ToList();
The benefit of this approach is that you can compare properties to arbitrary deep level i.e you can compare Hours, Minutes,Seconds etc. in your query. The second query is tested in Entity framework 5.

Related

How to convert a string into a datetime in Linq to Entities query?

My Linq to entities query is written as below.
The datatype of DATECOLUMN1 in my ORACLE database is of string.
Datetime FilterStartDate = DateTime.Now;
var query = from c in db.TABLE1
join l in db.TABLE2 on c.FK equals l.PK
where (FilterStartDate >= DateTime.ParseExact(l.DATECOLUMN1, "dd/MM/yyyy", CultureInfo.InvariantCulture) : false) == true
select c;
Writing above query gives me an error of not supported. How can I convert DATECOLUMN1 into a datetime to compare it.
P.S. I do not have control over database schema, so changing datatype of column in Oracle database is not a feasible solution for me.
In you Model, add the following property to your partial class TABLE2:
public DateTime DATECOLUMN1_NEW
{
get
{
return DateTime.ParseExact(DATECOLUMN1, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
set { }
}
Then, in you LINQ query, use DATECOLUMN1_NEW (it's already in DateTime format) in place of DATECOLUMN1.
Erm.. I think the problem you are having is that you are putting ": false" in there.
It looks like you are trying to use a condtional operator (?:) but you forgot the "?".
I don't think you actually need this as you are just trying to determine if the date is greater or not. Also if ParseExact fails it will throw an exception (not what you want) so you should use TryParse instead and handle the true/false returned and the out value to determine whether or not the date is (a) Actually a date (b) less then FilterStartDate.
You can use two alternatives:
Use the function described in the answer here: How to I use TryParse in a linq query of xml data?
Use the following fluent syntax version which I think is more readable.
var query = db.Table1.Join(db.Table2, x => x.FK, y => y.PK, (x, y) => x).Where(x =>
{
DateTime Result;
DateTime.TryParse(x.Date, out Result);
return DateTime.TryParse(x.Date, out Result) && FilterStartDate >= Result;
});

LINQ query with Timestamp column comparison in NHibernate

I am using automapping with Fluent NHibernate, and have used the following code to ensure that NHibernate does not strip away the milliseconds:
public class TimestampTypeConvention : IPropertyConvention, IPropertyConventionAcceptance
{
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => x.Type == typeof(DateTime) || x.Type == typeof(DateTimeOffset));
}
public void Apply(IPropertyInstance instance)
{
instance.CustomType<TimestampType>();
}
}
This works quite well, so the data is stored correctly in the database.
However, when I run the following LINQ query, I don't get a match where I would expect it:
bool isDuplicate = session.Query<TagData>()
.Any(x => x.TagName == message.EventTag.TagName
&& x.TimeStamp == message.EventTag.TimeStamp.UtcDateTime);
The resulting SQL looks like this, and explains why this doesn't work:
select tagdata0_."Id" as column1_0_, tagdata0_."TagName" as column2_0_,
tagdata0_."TimeStamp" as column3_0_, tagdata0_."Value" as column4_0_,
tagdata0_."QualityTimeStamp" as column5_0_, tagdata0_."QualitySubstatus" as column6_0_,
tagdata0_."QualityExtendedSubstatus" as column7_0_, tagdata0_."QualityLimit" as column8_0_,
tagdata0_."QualityDataSourceError" as column9_0_, tagdata0_."QualityTagStatus" as column10_0_,
tagdata0_."TagType" as column11_0_ from "TagData" tagdata0_
where tagdata0_."TagName"=:p0 and tagdata0_."TimeStamp"=:p1 limit 1;
:p0 = 'VALVE_HW_CMD' [Type: String (0)],
:p1 = 01.03.2013 16:51:30 [Type: DateTime (0)]
How can I force the generated query to use the full precision?
BTW, message.EventTag.TimeStamp is a DateTimeOffset
I was fooled by the logging output: The actual SQL (taken from the PostgreSQL log file) looks like this:
SELECT this_."Id" as column1_0_0_, this_."TagName" as column2_0_0_,
this_."TimeStamp" as column3_0_0_, this_."Value" as column4_0_0_,
this_."QualityTimeStamp" as column5_0_0_, this_."QualitySubstatus" as column6_0_0_,
this_."QualityExtendedSubstatus" as column7_0_0_, this_."QualityLimit" as column8_0_0_,
this_."QualityDataSourceError" as column9_0_0_, this_."QualityTagStatus" as column10_0_0_,
this_."TagType" as column11_0_0_ FROM "TagData" this_
WHERE this_."TimeStamp" = ((E'2013-03-01 16:51:30.509498')::timestamp)
That's the real reason that it didn't work quite as expected: The timestamp column in PostgreSQL only has microsecond accuracy, whereas the DateTimeDiff here has the value of 16:51:30.5094984, which means 1/10th of a microsecond accuracy. The only way to preserve the full accuracy seems to be to store the ticks in the database.
(Another reason for my confusion was that I received the duplicate messages from MassTransit more or less simultaneously on different threads, so checking the DB for duplicates of course didn't always work. O, the wonders of multithreading!)

Why can't I cast nullable DateTime as string in a LinQ query?

I am trying to take a DateTime value, and if it is not null return the Short Time String. My query looks like this:
(TimeIn is NOT NULLABLE, whereas TimeOut is NULLABLE)
var times = from t in db.TimePostings
where t.MemberID == member.MemberID
select new
{
Date = t.TimeIn.ToShortDateString(),
TimeIn = t.TimeIn.ToShortTimeString(),
TimeOut = t.TimeOut.HasValue ? t.TimeOut.Value.ToShortTimeString() : "-------"
};
gvTimePostings.DataSource = times;
gvTimePostings.DataBind();
but this fails when I try to databind with the error:
Could not translate expression 'Table(TimePosting).Where(t =>
(t.MemberID == Invoke(value(System.Func1[System.String])))).Select(t
=> new <>f__AnonymousType84(Date = t.TimeIn.ToShortDateString(), TimeIn = t.TimeIn.ToShortTimeString(), TimeOut =
IIF(t.TimeOut.HasValue, (t.TimeOut ??
Invoke(value(System.Func`1[System.DateTime]))).ToShortTimeString(),
"-------"), Hours = ""))' into SQL and could not treat it as a local
expression.
I also get a similar error if I try to use:
TimeOut = t.TimeOut.HasValue ? Convert.ToDateTime(t.TimeOut).ToShortTimeString() : "-------"
however, if I change the TimeOut property to:
TimeOut = t.TimeOut.HasValue ? t.TimeOut.ToString() : "-------",
it works fine, but does not format the time like I want it (shortTimeString).
what's up with that?
As others have said, the problem is with trying to convert ToShortDateString etc to SQL. Fortunately, this is easy to fix: fetch the data with SQL, then format it in .NET:
var timesFromDb = from t in db.TimePostings
where t.MemberID == member.MemberID
select new { t.TimeIn, t.TimeOut };
var times = from t in timesFromDb.AsEnumerable()
select new
{
Date = t.TimeIn.ToShortDateString(),
TimeIn = t.TimeIn.ToShortTimeString(),
TimeOut = t.TimeOut.HasValue
? t.TimeOut.Value.ToShortTimeString()
: "-------"
};
The call to AsEnumerable() here basically means, "stop trying to process the query using SQL; do the rest in LINQ to Objects".
ToShortTimeString() has no translation in SQL. Because of that, converting the statement into a single SQL statement fails and the exception is thrown.
If you break the statement into two calls (one to retrieve the data and another to create the projection), things will work just fine:
// must call ToList to force execution of the query before projecting
var results = from t in db.TimePostings
where t.MemberID == member.MemberID
select new { t.TimeIn, t.TimeOut };
var times = from t in results.AsEnumerable()
select new
{
Date = t.TimeIn.ToShortDateString(),
TimeIn = t.TimeIn.ToShortTimeString(),
TimeOut = t.TimeOut.HasValue ?
t.TimeOut.Value.ToShortTimeString() :
"-------"
};
Have you tried:
TimeOut = t.TimeOut.HasValue ? t.TimeOut.ToString("d") : "-------",
This will normally give the short format of the DateTime. Whether it works or not will depend on whether it can be translated to SQL or not.
If it doesn't work you'll have to break the query into two parts. The first gets the data, the second format it. You'll have to convert the first query to a list (.ToList()) to force the SQL to be evaluated.
Simply, it's not supported by this specific linq provider.
Your linq query is converted into an expression tree. It is up to the SQL Linq provider to convert this expression tree into SQL. Understandably, it does not have the capability to translate every single .NET function.
Your solution is to explicitly run the SQL by calling ToArray or ToList, and then allow LinqToObjects to handle the rest.
var times = from t in db.TimePostings
where t.MemberID == member.MemberID
select new {
TimeIn = t.TimeIn,
TimeOut = t.TimeOut
};
var timesFormated = times.ToArray() // Runs the query - any further processing will be run in memory by the local .NET code
.Select(t => new {
Date = t.TimeIn.ToShortDateString(),
TimeIn = t.TimeIn.ToShortTimeString(),
TimeOut = t.TimeOut.HasValue ? t.TimeOut.Value.ToShortTimeString() : "-------",
Hours = ""
}
);
Your query is transformed by LINQ to an SQL that is fired against your database, and there is obviously no way to translate t.TimeOut.Value.ToShortTimeString() to SQL.
Possible solutions are:
First fetch your data from database (by calling .ToList() or .ToArray() on your LINQ query), that converts your IQueryable<> into IEnumerable<> and then apply your transformation for every row fetched.
Use a view that takes the original table and performs the conversion using CONVERT() function on the SQL Server and use it as the source for your Linq-to-SQL class. That would be performanter, but requires some server-side changes.
I had the same problem in a project in vb.net.
The solution I've found is based on the use of:
if(table.field.hasvalue, table.field.value.ToShortDateString, string.format("NULL"))
In this case, if the selected field (table.field) has a value this is converted into a date string otherwise if the field hasn't a value the output field is filled with string "NULL"

compare the dates with linq

I have this code:
i.SpesaVitto = db.TDP_NotaSpeseSezB.Where(p => p.GiornoFine == null &&
((DateTime)p.Giorno).Date == ((DateTime)i.Data).Date &&
p.MissioneID == missioneID).Sum(p => p.Costo);
If i launch it i obtain this error:
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
how can i compare the datetimes field without the hours part
thanks
Well this is certainly not the most efficient way to do it, but you can try something like:
i.SpesaVitto = db.TDP_NotaSpeseSezB.Where(p => p.GiornoFine == null &&
(new DateTime((p.Giorno as DateTime).Year, (p.Giorno as DateTime).Month, (p.Giorno as DateTime).Day) == (new DateTime((i.Data as DateTime).Year, (i.Data as DateTime).Month, (i.Data as DateTime).Day) &&
p.MissioneID == missioneID).Sum(p => p.Costo);
Depending on the requirements I would probably implement something cleaner and faster but it would depend on how the dates are stored in your database.
Check out this question it looks like the syntax error may be in your SQL, not in your LINQ. The asker in that question had written:
SQL ------
Select
EmployeeNameColumn
From
EmployeeTable
WHERE StartDateColumn.Date <= GETDATE() //Today
SQL ------
When they should have written:
SQL ------
Select
EmployeeNameColumn
From
EmployeeTable
WHERE StartDateColumn <= GETDATE() //Today
SQL -
solution for your problem will be the "SqlFunctions class and DateDiff" http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.aspx

date difference with linq

With this code:
i.SpesaAlloggio = db.TDP_NotaSpeseSezB.Sum(p => p.Costo / (((DateTime)p.DayEnd)
.Subtract((DateTime)p.DayStart).Days + 1));
I receive this error:
LINQ to Entities does not recognize the method
'System.TimeSpan Subtract(System.DateTime)' method, and this method cannot be
translated into a store expression.
How can I do this?
Use a calculated DB field and map that. Or use SqlFunctions with EF 4 as LukLed suggested (+1).
I wrote a function for removing time:
public static DateTime RemoveHours(DateTime date)
{
int year = date.Year;
int month = date.Month;
int day = date.Day;
return new DateTime(year, month, day);
}
and changed filtering condition:
var query =
from trn in context.IdentityTransactions
where trn.ClientUserId == userId && trn.DateDeleted == null
orderby trn.DateTimeCreated
select new
{
ClientServerTransactionID = trn.ClientServerTransactionID,
DateTimeCreated = trn.DateTimeCreated,
ServerTransDateTime = trn.ServerTransDateTime,
Timestamp = trn.Timestamp,
Remarc = trn.Remarc,
ReservedSum = trn.ReservedSum,
};
if (dateMin.HasValue && dateMin.Value > DateTime.MinValue)
{
DateTime startDate = Converters.RemoveHours(dateMin.Value);
query = from trn in query
where trn.DateTimeCreated >= startDate
select trn;
}
if (dateMax.HasValue && dateMax.Value > DateTime.MinValue)
{
var endDate = Converters.RemoveHours(dateMax.Value.AddDays(1.0));
query = from trn in query
where trn.DateTimeCreated < endDate
select trn;
}
dateMin and dateMax are nullable types and may be not set in my case.
Try (it is not very efficient, but it will work):
i.SpesaAlloggio = db.TDP_NotaSpeseSezB.ToList()
.Sum(p => p.Costo / (((DateTime)p.DayEnd)
.Subtract((DateTime)p.DayStart).Days + 1));
EDIT : This will be extremely slow for large tables, because it transfers whole table content form server
Entity Framework tries to translate your expression to SQL, but it can't handle ((DateTime)p.DayEnd).Subtract((DateTime)p.DayStart). You have to make it simpler. ToList() gets all rows and then makes the calculation on application side, not in database.
With EF4, you could use SqlFunctions DateDiff
With EF1, you could create calculated field or view with this field and make calculation based on this field.

Resources