c# - Linq 实体 4.0 ('Include' ) : In search of an elegant way

标签 c# linq entity-framework

我正在自学 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 的参数似乎不起作用,因为它只排除字符串(见下图):enter image description here

最佳答案

编辑:在问题更改为 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/

相关文章:

大列表的 C# Linq 性能

.net - Visual Studio 2019 .EDMX 从数据库更新模型不起作用

asp.net-mvc-3 - Entity Framework : ViewModel to Domain Model

循环内的 C# SqlConnection

c# - IIS调试在Windows 2012服务器IIS 8.0

c# - 为什么 DefaultIfEmpty 是这样实现的?

c# - 在类构造函数中将 icollection 设置为列表时,如何通过索引从 icollection 中获取项目?

c# - 如何使用 SQL 参数从 SQL Server 获取数据集

c# - 如何通过反射执行带有可选参数的私有(private)静态方法?

c# - 无法将类型 'bool' 隐式转换为 'system.threading.tasks.task bool'