Alex Rivera | Logout

Reusing Linq to Entities' Expression<Func<T, TResult> in Select and Where calls

Asked 2010-03-15T11:44:09.740
14

Suppose I have an entity object defined as

public partial class Article  
{  
    public Id
    {
        get;
        set;
    }  
    public Text
    {
        get;
        set;
    }  
    public UserId
    {
        get;
        set;
    }  
}

Based on some properties of an Article, I need to determine if the article can be deleted by a given user. So I add a static method to do the checking. Something like:

public partial class Article  
{  
    public static Expression<Func<Article, bool>> CanBeDeletedBy(int userId)
    {  
        //Add logic to be reused here
        return a => a.UserId == userId;
    }  
}

So now I can do

using(MyEntities e = new MyEntities())  
{
    //get the current user id
    int currentUserId = 0;

    e.Articles.Where(Article.CanBeDeletedBy(currentUserid));  
}

So far so good. Now I want to reuse the logic in CanBeDeletedBy while doing a Select, something like:

using(MyEntities e = new MyEntities())  
{
    //get the current user id
    int currentUserId = 0;

    e.Articles.Select(a => new  
    {  
        Text = a.Text,  
        CanBeDeleted = ???  
    };  
}

But no matter what I try, I can't use the expression in the select method. I guess that If I can do

    e.Articles.Select(a => new  
    {  
        Text = a.Text,  
        CanBeDeleted = a => a.UserId == userId
    };  

Then I should be able to use the same expression. Tried to compile the expression and call it by doing

    e.Articles.Select(a => new  
    {  
        Text = a.Text,  
        CanBeDeleted = Article.CanBeDeletedBy(currentUserId).Compile()(a)
    }; 

but it won't work either.

Any ideas on how to get this to work? Or if it isn't possible, what are the alternatives to reuse business logic in both places?

Thank

Edit
Report

1 Answer

3

What I did is I used PredicateBuilder which is a class in LinqKit and also AsExpandable() http://www.albahari.com/nutshell/linqkit.aspx to build up expressions and I stored them Statically as

public readonly Expression<Func<T,bool>>

in a static class. Each expression was building on a previous expression thus reducing the amount of duplication.

As the previous question by Marc Gravell suggests this kinda thing is a black art, but thankfully a lot of the work has been done by other poeple.

answered 2010-11-03T15:13:11.077

Your Answer