I am unsure if this is possible yet, as I am just diving into Entity Framework 6. We are migrating away from Linq2Sql, but have many user based queries in our engine. We dynamically compile some code based on user requirements, and have to maintain backward compatibility.
An example of some dynamic query that is passed in from the legacy Linq2Sql may looks like this (stripped down, this is only a sample):
from item in context.SomeTableOrView
let sub = from sub1 in context.SomeTableOrView where
sub1.DataTimeStamp > item.DataTimeStamp.AddMinutes(60) &&
sub1.DataTimeStamp < item.DataTimeStamp.AddMinutes(300)
select posSub1 where
sub.Take(1).Any()
select item
Of course, Entity Framework does not have any kind of .AddMinutes(x)
support, and you must use the new DbFunctions static methods. We can't break the code, so we must retrofit it. The first solution that comes to mind, is just to replace the text where anything that has .AddMinutes(x)
, or .AddSeconds(x)
, or whatever we do around DateTime
, and just replace with the new functions and be done with it. This is all pre-compile, so that technically would work. I just suck at regular expressions. I would gladly accept that as an answer if someone knows how I would do that though.
But I would like understand how EntityFramework works with regards to extension methods. Since the return of DateTime.AddMinutes(x)
returns a new DateTime
, Could I instead create an extension method to return an expression that would do the equivalent of DbFunctions.AddMinutes(time, increment)
or something creative like that? DbFunctions is static, so I cant return a Func<DbFunctions>
.
Thoughts / Suggestions. Thanks!
Updated - Ivan gives a great updated answer for anyone looking at this. Less error prone to the below answer, and quite slick IMO. enter link description here