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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With