我正在尝试查找并运行一个名为CompiledQuery的名称。如何按名称访问已编译的查询,如何调用委托?
这是我能得到的 - 我收到错误'错误绑定到目标方法'
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);
//省略了其他编译查询,但结果是实现公共接口IProjectObject的IQueryable对象
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
}
}
}
答案 0 :(得分:0)
你可能会做一些漫长的尝试识别Func&lt; ...&gt;类型字段的方法。使用DataContext作为返回IQueryable的第一个参数,但您可能会发现添加自定义属性要容易得多:
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class DynamicQueryAttribute : Attribute { }
...然后您可以将其添加到您的字段中:
[DynamicQuery]
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 IQueryable<IProjectObject> ExecuteQuery(Type ownerType, string name, params object[] args)
{
var query = typeof(ownerType)
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(f =>
(f.GetCustomAttributes(typeof(DynamicQueryAttribute), false).Length > 0)
&& (f.Name.ToLowerInvariant() == name.ToLowerInvariant()))
.Select(f => (Delegate) f.GetValue(null))
.SingleOrDefault();
if (query == null)
return null;
return (IQueryable<IReportObject>)query.DynamicInvoke(args);
}
用法:
var results = ExecuteQuery(
typeof(ActivityRepository),
"GetCompiledLatestProjects",
dataContext,
projectId);
希望有所帮助:)