I'm trying to find and run a CompiledQuery given the name. How do I access the compiled query by name and how do I then invoke the delegate?
Here's as far as I can get - I get the error 'Error binding to target method'
public class ActivityRepository
{
private readonly ActivityDataContext _db;
public ActivityRepository()
{
_db = new ActivityDataContext();
}
public static Func<ActivityDataContext, int, IQueryable<ProjectObject>>
GetCompiledLatestProjects = CompiledQuery.Compile
((ActivityDataContext db, int projectId) =>
from c in db.projectObjects
where c.projectId == projectId
select c);
public static Func<ActivityDataContext, Guid, IQueryable<Report>>
GetCompiledReports = CompiledQuery.Compile
((ActivityDataContext db, Guid itemId) =>
from c in db.Reports
where c.reportObjectId == itemId
select c);
// Other compiled queries ommitted, but the results are IQueryable objects that implement a common interface IProjectObject
delegate IQueryable<IProjectObject> MyDelegate();
static MyDelegate GetByName(object target, string methodName)
{
return (MyDelegate)Delegate.CreateDelegate
(typeof(MyDelegate), target, methodName);
}
public IList<Results> GetResults(string reportName)
{
IQueryable<ProjectObject> projectItems = GetLatestProjectObjects(projectId, quantity);
foreach (projectObject o in projectItems)
{
MyDelegate del = GetByName(this, reportName);
var dbReport = (IProjectObject) GetCompiledReports(_db, o.itemId).FirstOrDefault();
// add results to List and return
}
}
}
You can probably do some long winded way of trying to identify any fields of type Func<...> with a DataContext as the first argument that return IQueryable, but you might find it a lot easier to just add a custom attribute:
...which you can then add to your field:
You can then select the query based on that, and its name:
Usage:
Hope that helps :)