4
votes

This code is producing an error:

void GetLog()
{
    List<CAR_STATUS_LOGS> logs = null;
    using (TESTEntities ctx = new TESTEntities())
    {
        logs = 
            ctx.CAR_STATUS_LOGS
                .Where(a => SqlFunctions.DatePart("DAY", a.TIMEMARK) == 1)
                .ToList();
    }
}

The error is this:

LINQ to Entities does not recognize the method 'System.Nullable`1[System.Int32] DatePart(System.String, System.Nullable`1[System.DateTime])' method, and this method cannot be translated into a store expression.

I can't see what I am doing wrong with the SqlFunctions.DatePart. The column TIMEMARK is a Sqlserver DateTime type.
Any ideas?

4
this is a runtime error, not a compile time error, right ? - Raphaël Althaus
Yes this is a runtime error it compiles ok. - Paul
Could you maybe look at the results, if you do (instead of the Where) : .Select(a => SqlFunctions.DatePart("day", a.TIMEMARK)).ToList() - Raphaël Althaus
Unfortunately it returns the same run time error as before. - Paul
@RaphaëlAlthaus what is the use for null check of TIMEMARK I mean the second argument is nullable in datepart I guess - Neel

4 Answers

15
votes

You can use System.Data.Entity.SqlServer.SqlFunctions from assembly EntityFramework.SqlServer.dll (Entity Framework 6.1.3), example:

myTable.Where (w => 
    (System.Data.Entity.SqlServer.SqlFunctions.DatePart("weekday", w.Data).Value == 1);
0
votes
DbFunctions.DiffDays(Date1,Date2)==1
-1
votes

write day instead of DAY

SqlFunctions.DatePart("day", a.TIMEMARK) == 1).ToList();

because day stands for

dd, d

for more details :-

http://www.w3schools.com/sql/func_datepart.asp

-1
votes

if a.TIMEMARK is a datime, you cann access the day with a.TIMEMARK.Day