PAY ATTENTION . I know how to get around this. I am NOT looking for a solution, I am looking for clarity of the problem itself.
class Program { static void Main(string[] args) { using (var context = new TestDbContext()) { var eventsFound = context.Events .Where(e => e.EventDate >= DateTime.Now.AddDays(-1) && e.EventDate <= DateTime.Now.AddDays(+1) ) .ToList(); } } } public class TestDbContext : DbContext { public DbSet<Event> Events { get; set; } } public class Event { public int EventId { get; set; } public DateTime EventDate { get; set; } }
Ok, so the above program failed:
LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)' method, and this method cannot be translated into a store expression.
Why LINQ cannot distinguish a database function from an object function. The system must be smart enough to understand that the AddDays function is part of a DateTime object. Then it must first enable this function, and then after all the functions in the request have been resolved, convert to SQL and execute them with the database.
I am sure this is much more complicated, but I would like to understand why.
========= EDIT ===============
Thus, the above was not really a good example, since "AddDays" is a function that exists in both .NET and SQL. How about when I change it to an independent function where ambiguity cannot exist.
t
public class Event { public int EventId { get; set; } public DateTime EventDate { get; set; } public DateTime ReturnDateNowExample() { return DateTime.Now; } } static void Main(string[] args) { var myEvent = new Event {EventDate = new DateTime(2013, 08, 28)}; using (var context = new TestDbContext()) { var eventsFound = context.Events .Where(e => e.EventDate >= myEvent.ReturnDateNowExample() ) .ToList(); } }
And this is if the DateTime object is ambiguous, and then replace it with a string / int object.
source share