Reusing LINQ expressions created in a Portable Class Library

474 Views Asked by At

Is it possible to create a LINQ expression inside a Portable Class Library and reuse the expression in other parts of the application? One handy use case for me would be to utilize these expressions in CompiledQuerys across platforms instead of copy/pasting the same code multiple times.

All my attempts so far ended up in throwing some more or less meaningless runtime exception (NullReferenceException, Column not found..). I'm guessing LINQ expressions in a PCL are handled differently than for example in a WP application?

public class SomeClassNotInPCL
{
    private static readonly Func<Context, int, MyClass> CompiledQuery = 
        CompiledQuery.Compile(ClassFarAway.MethodInsidePCL());
}

public class ClassFarAway
{
    private static Expression<Func<IContext, int, MyClass>> MethodInsidePCL()
    {
        return (context, id) => context.MyClass.FirstOrDefault(m => m.Id == id);
    }
}
1

There are 1 best solutions below

1
On

How about something like this?

var commonExpressions = new Dictionary<CommonRegEx, Regex>();

public enum CommonRegEx{
   Phone,
   Email,
   SSN
}