views:

882

answers:

2

My entity has a property which is derived from other properties

public class MyClass
{
    public DateTime Deadline { get; set; }
    public Severity Severity 
    {
        return (DateTime.Now - Deadline < new TimeSpan(5, 0, 0, 0)) ? Severity.High : Severity.Low;
    }
}

is there a way I can modify the following

return repository.Query().Where(myClass => myClass.Severity == High);

so that the where clause evaluates in sql rather than in code?

I tried to do something like this, but to no avail

public class MyClass
{
    public DateTime Deadline { get; set; }
    public Func<MyClass, bool> SeverityFunc = (DateTime.Now - Deadline < new TimeSpan(5, 0, 0, 0)) ? Severity.High : Severity.Low;
    public Severity Severity 
    {
        return SeverityFunc.Invoke(this);
    }
}

return repository.Query().Where(myClass => myClass.SeverityFunc(myclass) == High);

I'm guessing because the func cant be evaluated to SQL. Is there some other way to do this without ending up with duplicate calculations for severity

Any help appreciated, ta

Edit: This is a simplified version of what im trying to do, i'm looking for answers that cover the theory of this rather than a specific fix (though still welcome). Im interested in whats possible, and best practices to achieve this sort of thing.

Andrew

+1  A: 

I have used something similar on a mapper. Make sure to wrap the Func on on Expr, like:

public Expr<Func<MyClass, bool>> SeverityFunc ...

By wrapping it with expr linq2sql will be able to look at the full expression and translate appropiately. I haven't used it as part of a class instance like the one you have, so I am not sure how that would affect it.

Regarding on where to put it, I had to move on the last time I worked on a similar scenario, in my case it ended up in the mapper, but mostly because it was more a mapping concern from an awfully database schema than domain logic. I didn't even had the property dynamically calculated on the domain entity for that matter (a different scenario for sure).

eglasius
A: 

One option is the LINQ Dynamic Query Library, See http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Another option is to use the PredicateBuilder from http://www.albahari.com/nutshell/predicatebuilder.aspx

Hope this answers your question, Roelof.

roelofb