tags:

views:

70

answers:

1

I issued a SQL on SQL Server 2000:

select * from Employee where LastUpdateDate >=DateAdd(yyyy,-1,Getdate())

It works fine and got some records.

Then I write a Linq for the same purpose:

EntityQuery<Employee> query = from e in ctx.GetEmployeeQuery()
                               where e.DateCreated >= DateTime.Today.AddYears(-1)

but I got null from the result.

How to fix it?

+3  A: 

Linq to Entities doesn't support the AddYear method. It does not know how to translate this into SQL. The solution is to precalc the value.

var targetDate = DateTime.Now.AddYears(-1)
EntityQuery<Employee> query = from e in ctx.GetEmployeeQuery()
                               where e.DateCreated >= targetDate
olle
This is better code, anyhow, as it doesn't involve recalculating the targetDate.
Steven Sudit
in general compilers are pretty good at optimizing those things although in the case of a date I hope it wouldn't since the year might change during execution :)
olle
Yes, it would have no way to know that it's perfectly fine for it to cache the calculated date, so it would probably have to recreate it each time. In fact, we probably don't even want the target date to shift, performance aside.
Steven Sudit