Linq compiled queries without passing context

Consider this compiled linq-to-sql query:

private static Func<LINQDBDataContext, string, IQueryable<Pet>> QueryFindByName = CompiledQuery.Compile(( MyLinqDataContext context, string name) => from p in context.Pets where p.Name == name select p); 

But I already have a private reference to the context in the class, and I want to be able to mark the request as public, without exposing the context, for example.

 private static MyLinqDataContext context = SomeUtilityClass.GetMeMyContext(); //... public static Func<string, IQueryable<Pet>> QueryFindByName = CompiledQuery.Compile((string name) => from p in this.context.Pets where p.Name == name select p); //doesn't compile as expects TArg0 to be a DataContext. 

Is there a way to do this without creating a public wrapper function for each request?

+4
source share
1 answer

Is your reference to a static context, i.e. do you have one context by type? This is not a good idea for me. In any case, leaving this on the one hand, you can do:

 // Private version which takes a context... private static Func<LINQDBDataContext, string, IQueryable<Pet>> QueryFindByNameImpl = CompiledQuery.Compile(( LINQDBDataContext context, string name) => from p in context.Pets where p.Name == name select p); // Public version which calls the private one, passing in the known context public static Func<string, IQueryable<Pet>> QueryFindByName = name => QueryFindByNameImpl(contextFromType, name); 

EDIT: Well, if you don't like this approach, you can try writing your own generic wrappers around CompiledQuery.Compile . For instance:

 public static class LinqHelpers { public static Func<TArg0, TResult> Compile<TContext, TArg0, TResult> (this TContext context, Expression<Func<TContext, TArg0, TResult>> query) where TContext : DataContext { Func<TContext, TArg0, TResult> compiled = CompiledQuery.Compile(query); return arg => compiled(context, arg); } } 

(And so on for more options.)

I have not even tried to compile this, but I think it will work. Then you will use it as follows:

 private static MyLinqDataContext context = SomeUtilityClass.GetMeMyContext(); public static Func<string, IQueryable<Pet>> QueryFindByName = context.Compile ((LINQDBDataContext context, string name) => from p in context.Pets where p.Name == name select p); 

It creates a wrapper anyway, but at least you only need to do it in one place. If your objection to creating wrappers was something other than its boredom / code, please provide more details.

+3
source

All Articles