1
CREATE TABLE PersonTask
(
PersonId INT NOT NULL,
WeekId INT NOT NULL,
WeekDaysTaskId INT,
WeekEndTaskId INT
)
GO
CREATE TABLE Task
(
Id INT PRIMARY KEY,
[Description] VARCHAR(250) NOT NULL
)
GO
INSERT INTO Task(Id, [Description]) VALUES(1, 'Task-01')
INSERT INTO Task(Id, [Description]) VALUES(2, 'Task-02')
INSERT INTO Task(Id, [Description]) VALUES(3, 'Task-03')
GO
INSERT INTO PersonTask(PersonId, WeekId, WeekDaysTaskId, WeekEndTaskId) VALUES(1, 1, NULL, 1)
INSERT INTO PersonTask(PersonId, WeekId, WeekDaysTaskId, WeekEndTaskId) VALUES(1, 2, 2, NULL)
INSERT INTO PersonTask(PersonId, WeekId, WeekDaysTaskId, WeekEndTaskId) VALUES(1, 3, 3, 3)
GO

SELECT 
        PT.PersonId, 
        WeekId,
        'Not on Bench' as [Status]
    FROM PersonTask AS PT
    INNER JOIN Task AS T ON T.Id IN (PT.WeekDaysTaskId, PT.WeekEndTaskId)
    WHERE WeekId = 3/*Param-1*/ and PersonId = 1/*Param-2*/

我正在尝试编写与上述 T-sql 语句等效的 linq 查询,但徒劳无功。有人可以帮助使用 C# Linq 查询来获取上述 T-SQL 语句。

4

1 回答 1

1

必须类似于(前提是您有 personTaskQueryable 和 taskQueryable):

from pt in personTaskQueryable
from t in taskQueryable
where (t.Id == pt.WeekDaysTaskId || t.Id == pt.WeekEndTaskId)
    && pt.WeekId == 3 && pt.PersonId == 1
select new { pt.PersonId, pt.WeekId, Status = "Not on Bench" }

我没有尝试,因为我直接在答案文本框中进行编码,但 Linq 文档说你不能用“join”运算符做这样的事情,因为它只支持 equijoins。

解决方案是首先构建笛卡尔积并从那里限制结果集。

于 2013-01-09T16:24:11.953 回答