我正在自学 Linq to entities,我有一点疑问。看看下面的方法。它为 List of WorkflowsInProgress
中的每个项目返回最新完成的任务。在我使用 TasksInProgress 字段
的其他方法中调用此方法,但我也在使用 链接的 Tasks 和 WorkflowInProgress
的属性。正如您将看到的,我已将 Include
添加到查询中。
public List<TasksInProgress> GetLatestTaskForWorkflowsInProcess(List<WorkflowInProgress> pWorkflowsInProcess)
{
List<TasksInProgress> tasksLst = new List<TasksInProgress>();
List<Int64> workflowIds = pWorkflowsInProcess.Select(w => w.Id).ToList();
using (TaskWorkflowEntities myDatacontext = new TaskWorkflowEntities())
{
tasksLst = (from taskP in myDatacontext.TasksInProgress.Include("Tasks").Include("WorkflowInProgress")
where (taskP.RunningState == (int)WorkflowRunningStates.Completed) &&
workflowIds.Contains(taskP.WorkflowInProgressId) &&
taskP.Completed == (from sTaskP in myDatacontext.TasksInProgress
where sTaskP.WorkflowInProgressId == taskP.WorkflowInProgressId
group sTaskP by sTaskP.WorkflowInProgressId into gSTaskP
select gSTaskP.Max(g => g.Completed)).FirstOrDefault()
select taskP).ToList<TasksInProgress>();
}
return tasksLst;
}
我的问题是:
'Is there a more elegant way to include other tables inside a Query?' Because i don't like those hardcoded objectnames just sitting there' (Imagine if the tablename changes...)
Or is there any other way that i can use to include the fields of linked objects/navigational properties?
注意:上面这个方法的例子:
foreach(TasksInProgress taskInProc in _taskWorkflowS.GetLatestTaskForWorkflowsInProcess(currentWorkflowsInProcess))
{
//Do something with (int)taskInProc.Tasks.TaskOrder
//Do something with taskInProc.WorkflowInProgress.WorkflowId
// ...
//for Instance
int i = 0;
i = _taskWorkflowS.GetAmountOfTasksForWorkflow(taskInProc.WorkflowInProgress.WorkflowId, (int)taskInProc.Tasks.TaskOrder)
if (i > 0 )
{ ... }
}
更新:
使用 lambda 表达式作为 Include
的参数似乎不起作用,因为它只排除字符串(见下图):
最佳答案
编辑:在问题更改为 Entity Framework 4.0 之前回答。这仅适用于 EF 4.1 及更高版本
你可以拥有
.Include(o => o.Tasks)
如果你添加
using System.Data.Entity;
至少你那时没有使用字符串,如果表格改变你会得到错误
关于c# - Linq 实体 4.0 ('Include' ) : In search of an elegant way,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23103762/