Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime manipulation inside Linq to entities query

running this code:

public bool CheckTime(DateTime date, int UserID, int TotalTimeMin)
        {
            using (var context = new myDB())
            {         
                var assginments = from c in context.Assignments.Where(x=>(x.AssignmentDateTime < date && x.AssignmentDateTime.Value.AddMinutes(TotalTimeMin) > date) || 
                    (x.AssignmentDateTime < date.AddMinutes(TotalTimeMin))) select c;

                if(assginments != null) return false;
                else return true;
            }


        }

I get this error.

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

TotalTimeMin is int. I am not sure what cause this: AssignmentDateTime is DateTime? and maybe this is the problem ?

like image 330
Dani Avatar asked Jan 28 '11 20:01

Dani


1 Answers

Use EntityFunctions.AddMinutes (requires EF 4):

    public bool CheckTime(DateTime date, int UserID, int TotalTimeMin)
    {
        using (var context = new myDB())
        {         
            var assginments = context.Assignments
                                     .Where(x=>(x.AssignmentDateTime < date 
                                                && EntityFunctions.AddMinutes(x.AssignmentDateTime,TotalTimeMin) > date) 
                                                || (x.AssignmentDateTime < date.AddMinutes(TotalTimeMin)));

            if(assginments != null) return false;
            else return true;
        }
    }

Note that assignments will never be null (but it might be empty -- test assignments.Any()).

like image 142
Craig Stuntz Avatar answered Oct 24 '22 23:10

Craig Stuntz