31

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

1

2 Answers 2

60

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();
7
  • 1
    EntityFunctions is a new world for me !! thank you!! This worked really good. Jun 28, 2013 at 19:21
  • 2
    You should then "accept as answer". Cross the checkmark next to the answer. This will give credit to the person who helped you and help others quickly locate the correct answer.
    – Tormod
    Jun 28, 2013 at 19:27
  • Note that EntityFunctions will only work inside an EF context. Attempting to evaluate the method (i.e. on a local collection for unit tests) will throw an exception. Jun 28, 2013 at 20:42
  • 1
    Just found this post and implemented the above code, to be instructed that System.Data.Entity.Core.Objects.EntityFunctions is now obsolete, and is replaced by System.Data.Entity.DbFunctions. Nov 10, 2014 at 4:23
  • 2
    Thanks @BrettRigby, I've updated the answer for EF 6 Nov 10, 2014 at 15:22
6

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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.