Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First: Methods that can translate to SQL

I'm looking for a way to create a function that can be used in my Linq queries that will translate to SQL. Back when we were using Linq-to-SQL, I posed a similar question. The answer was to map to a UDF in the db. We're using the code first model because of the cleanliness of the model definition, but unfortunately there is no way to define functions, map to functions, and map to stored procs as far as I can tell (I guess the idea being that code first should generate the db, and I shouldn't be adding things to it). Doesn't seem very scale-able to me, since it allows no easy method for dealing with inefficiencies that may evolve over time, but that's neither here nor there...

Anyway, I know I can define predicate expressions that will translate to SQL that I can use in my queries like so:

public static Expression<Func<MyEntity, bool>> FilterMe(int comparisonNumber)
{
    return x => x.SomeProperty == comparisonNumber;
}

var query = MyEntities.Where(FilterMe(1));

Is this only possible for Expressions that return bool? I'm looking for something along the lines of:

var query = from m in MyEntities
            let endDate = GetEndDate(m.Start, m.Duration)
            where endDate <= DateTime.Now
            select m;

Is there some way to build GetEndDate in an expression function? The code within GetEndDate translates to SQL just fine when I write it long-hand in the query, but it's pretty long and confusing to read.

Edit - Oh and before someone answers with "Use SQLFunctions for DateAdd", my example is just that..an example. There are countless other ways I'd like to use this. Thanks in advance.

like image 761
Ocelot20 Avatar asked Jun 28 '12 14:06

Ocelot20


1 Answers

You can try LinqKit: http://www.albahari.com/nutshell/linqkit.aspx with .AsExpandable() and .Compile(), it allows the use of Expressions in your Linq queries.

like image 87
Guillaume86 Avatar answered Oct 27 '22 03:10

Guillaume86