Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DATEADD over column in LINQ - DateAdd is not recognized by LINQ

Tags:

c#

linq

I am trying to invalidate requests of friendship that were reponded less than 30 days ago.

var requestIgnored = context.Request
    .Where(c => c.IdRequest == result.IdRequest 
             && c.IdRequestTypes == 1 
             && c.Accepted == false 
             && DateTime.Now <= (((DateTime)c.DateResponse).AddDays(30)))
   .SingleOrDefault();

c.DateResponse is of type DateTime?. The error I am having is :

LINQ does not recognize the command .AddDays

like image 297
Bryan Arbelo - MaG3Stican Avatar asked Jun 28 '13 18:06

Bryan Arbelo - MaG3Stican


2 Answers

Edit: If you're using EntityFramework >= 6.0, use DbFunctions.AddDays. For older versions of Entity Framework, use EntityFunctions.AddDays:

var requestIgnored = context.Request
    .Where(c => c.IdRequest == result.IdRequest 
             && c.IdRequestTypes == 1 
             && c.Accepted == false 
             && DateTime.Now <= DbFunctions.AddDays(c.DateResponse, 30))
   .SingleOrDefault();
like image 156
Scott Wegner Avatar answered Sep 19 '22 22:09

Scott Wegner


You might try this:

var thirtyDaysAgo = DateTime.Now.AddDays(-30);
var requestIgnored = context.Request
    .Where(c => 
        c.IdRequest == result.IdRequest && 
        c.IdRequestTypes == 1 && 
        c.Accepted == false && 
        c.DateResponse.HasValue &&
        thirtyDaysAgo <= c.DateResponse.Value)
    .SingleOrDefault();
like image 24
p.s.w.g Avatar answered Sep 22 '22 22:09

p.s.w.g