0

我有 2 张桌子。1 个实体,每行 1 个。另一个只是我的 EntitiesID 和 EmployeeID 的映射表。我正在尝试编写一个 LINQ 方法,该方法从第一个表中返回所有实体,其中 EntityID 在由 EmployeeID 过滤的映射表中。

简化表结构示例 TaskTable: ID, Description, Status TaskViewTable: ID, TaskID, EmployeeID

因此,我想从 TaskTable 返回 ID 位于基于 EmployeeID 的 TaskViewTable 的子查询结果中的所有行。

在 LINQ 中执行此操作有什么帮助吗?我在两张桌子之间也设置了一对多。我知道有类似的问题,也许我很密集,但它们似乎并不完全适用于我所问的问题。(例如Linq Return Filtered Children

抱歉忘了显示我到目前为止的内容:

IQueryable<tblTask> tTask=context.GetTable<tblTask>();
return tTask.Where(t => t.tblTasksViews.Where(v => v.EmployeeID == empID))

然而,它不喜欢我whereunkown method Where(?)

4

2 回答 2

1

尝试这样的事情:

var query =
    from tt in TaskTable
    join tvt in TaskViewTable on tt.ID equals tvt.TaskID into xs
    where xs.Any(z => z.EmployeeID == empID)
    select tt;
于 2012-07-10T05:39:21.447 回答
1

这样的事情应该可以解决问题:

var tasks = tTask.Where(t => 
    tTaskView.Where(v => v.ID == empId).Select(v => v.TaskId).Contains(t.ID));

您可以将上述内容分为两个部分:

//1.) Get all task views for the employeeID and only select the mapped TaskId
var taskViews = tTaskView.Where(v => v.ID == empId).Select(v => v.TaskId); //taskViews = IEnumerable<int>

//2.) Then get all tasks from the filtered task ids  
var tasks = tTask.Where(t => taskViews.Contains(t.ID));

更新

//3.) Project filtered results into IEnumerable<Task>
return tasks.Select(t => new Task() 
{ 
    ID = t.ID, 
    ActionableID = t.ActionableID, 
    StatusID = t.StatusID, 
    TypeID = t.TypeID, 
    Description = t.Description 
});

当然,您可以将所有内容串成一个漂亮的单行:

public List<Task> GetTasks(int empId) 
{
    return tTask
        .Where(t => tTaskView.Where(v => v.ID == empId).Select(v => v.TaskId).Contains(t.ID))
        .Select(t => new Task() 
        { 
            ID = t.ID, 
            ActionableID = t.ActionableID, 
            StatusID = t.StatusID, 
            TypeID = t.TypeID, 
            Description = t.Description 
        }).ToList();
}
于 2012-07-10T06:20:29.797 回答