1

I have 2 DateTime values that have seconds I compare them with 2 other DateTimes these dont have seconds thats why I never get the result I want. Is it possible to remove the seconds from the DateTimes inside the Lambda expression

ListData = _UnitOfWork.Data.Query(x =>
                    x.DateTimeWithSeconds1 >= DateTimeWithoutSeconds1 && x.DateTimeWithSeconds2 <= DateTimeWithoutSeconds2).ToList();

Thats my Code right now that doesn't work

ListData = _UnitOfWork.Data.Query(x =>
                    x.DateTimeWithSeconds1.AddSeconds(-x.DateTimeWithSeconds1.Seconds) >= DateTimeWithoutSeconds1 && x.DateTimeWithSeconds2.AddSeconds(-x.DateTimeWithSeconds2.Seconds) <= DateTimeWithoutSeconds2).ToList();

And that is something i tried but i get an exception that says "LINQ to Entities does not recognize the method 'System.DateTime AddSeconds(Double)'"

Thanks in advance

NG.
  • 11
  • 5
  • 3
    `DateTime.AddSeconds` is not convertible to SQL statement in LINQ to Entities. You need to perform the operation outside the query or materialize it into LINQ to Objects instead. – Tetsuya Yamamoto Aug 10 '18 at 09:15
  • @TetsuyaYamamoto Do you know a way how I can remove the seconds in LINQ without DateTime.AddSeconds? – NG. Aug 10 '18 at 09:20
  • @NG.: You can use [`EntityFunctions.CreateDateTime`](https://msdn.microsoft.com/en-us/library/system.data.objects.entityfunctions.createdatetime(v=vs.110).aspx) to create one without seconds – Tim Schmelter Aug 10 '18 at 09:22
  • It's important to understand the difference between LINQ as an overarching technology and a LINQ provider. You can write any code supported by LINQ but, at run time, that code gets processed by a LINQ provider and how the code gets processed depends wholly on that LINQ provider. LINQ to Entities, which is the Entity Framework LINQ provider, needs to be able to map your LINQ code to SQL to execute against the database. There's no mapping of the `Date.AddSeconds` method to SQL code. The `EntityFunctions` class suggested is specifically mapped to SQL code, so you must use that for those actions. – jmcilhinney Aug 10 '18 at 09:23
  • You _could_ string format your date without seconds (`yyyy-MM-dd HH:mm`). I don't know about LINQ to Entities, but it's worth a try I guess. – Maxime Recuerda Aug 10 '18 at 09:25

0 Answers0