How to pass a Lambda Expression as method parameter with EF

Posted by Registered User on Stack Overflow See other posts from Stack Overflow or by Registered User
Published on 2012-04-07T23:01:06Z Indexed on 2012/04/07 23:29 UTC
Read the original article Hit count: 207

How do I pass an EF expression as a method argument?

To illustrate my question I have created a pseudo code example:

The first example is my method today. The example utilizes EF and a Fancy Retry Logic. What I need to do is to encapsulate the Fancy Retry Logic so that it becomes more generic and does not duplicate.

In the second example is how I want it to be, with a helper method that accepts the EF expression as an argument.

This would be a trivial thing to do with SQL, but I want to do it with EF so that I can benefit from the strongly typed objects.

First Example:

public static User GetUser(String userEmail)
{
    using (MyEntities dataModel = new MyEntities ())
    {
        var query =  FancyRetryLogic(() =>
        {
            (dataModel.Users.FirstOrDefault<User>(x => x.UserEmail == userEmail)));
        });

        return query;
    }
}

Second Example:

T RetryHelper<T>(Expression<Func<T, TValue>> expression)
{
    using (MyEntities dataModel = new (MyEntities ())
    {

        var query = FancyRetryLogic(() =>
                    {
                        return dataModel.expression
                    });
    }
}

public User GetUser(String userEmail)
{
    return RetryHelper<User>(<User>.FirstOrDefault<User>(x => x.UserEmail == userEmail))
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET