EntityFramework DateTime Linq

c# datetime entity-framework linq

Question

Entity Framework is what I'm utilizing in my application.

My Desk

-Article
-period
-startDate

I need matching records.DateTime.Now > startDate and (startDate + period) > DateTime.Now

Though I tested it, the code is now functional.

Context.Article
    .Where(p => p.StartDate < DateTime.Now)
    .Where(p => p.StartDate.AddDays(p.Period) > DateTime.Now)

I see the following error while running my code.

LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)' method, and this method cannot be translated into a store expression.

1
105
9/19/2016 11:14:50 AM

Accepted Answer

Your predicates within the Where clause are transformed to SQL when utilizing LINQ to Entity Framework. There is no translation to SQL for and that's why you're receiving that problem.DateTime.Add() it is reasonable.

Reading the results of the first Where query into memory and then using LINQ to Objects to complete the filtering might be a simple workaround:

Context.Article.Where(p => p.StartDate < DateTime.Now)
               .ToList()
               .Where(p => p.StartDate.AddDays(p.Period) > DateTime.Now);

If you're using.NET 4.0, you might also attempt the EntityFunctions.AddDays technique:

Context.Article.Where(p => p.StartDate < DateTime.Now)
               .Where(p => EntityFunctions.AddDays(p.StartDate, p.Period)
                   > DateTime.Now);

Remark: InEF 6 It is now 31: Zzz.

195
1/14/2014 7:53:47 PM

Popular Answer

I believe this is what the previous answer was trying to propose, but why not perform something that can be compared to a sql query rather than attempting to add days to p.startdat:

var baselineDate = DateTime.Now.AddHours(-24);

something.Where(p => p.startdate >= baselineDate)


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow