我们正在将实体框架纳入我的应用程序中。我已经将很多简单的存储过程转换为linq查询但是这个给我带来麻烦,我不确定我哪里出错了。我的大脑变成了果冻,我无法使它发挥作用。我将非常感谢您的帮助,请耐心等待。
我的SQL是:
SELECT ...
FROM tblProjectAssignment
INNER JOIN tblProjectAssignmentCollection
ON tblProjectAssignment.AssignmentID = tblProjectAssignmentCollection.AssignmentID
RIGHT OUTER JOIN tblCEQRPhaseIIUsers
ON tblProjectAssignment.UserID = tblCEQRPhaseIIUsers.UserID
LEFT OUTER JOIN tblCEQRAccessUserRole
ON tblCEQRPhaseIIUsers.UserRoleTypeID = tblCEQRAccessUserRole.UserRoleTypeID
我需要帮助将上面的内容转换为linq查询。我知道DefaultIfEmpty()
用于外连接,但是我运行查询时得到的结果不正确。所以,我需要的是tblCEQRPhaseIIUsers
以使所有结果与其他表中的相应结果无关。以下查询的行为与所有表都具有内部联接一样。
var query = from PATable in db.tblProjectAssignments
from PACTable in db.tblProjectAssignmentCollections.Where(la => la.AssignmentID == PATable.AssignmentID)
from UserTable in db.tblCEQRPhaseIIUsers.Where(la => la.UserID == PATable.UserID).DefaultIfEmpty()
from UserRoleTable in db.tblCEQRAccessUserRoles.Where(la => la.UserRoleTypeID == UserTable.UserRoleTypeID).DefaultIfEmpty()
where (UserTable.FirstName.ToLower().Contains(search.FirstName.Trim().ToLower()) || search.FirstName == null)
where (UserTable.LastName.ToLower().Contains(search.LastName.Trim().ToLower()) || search.LastName == null)
where (PACTable.CEQRNumber.ToLower().Contains(search.CEQRNumber.Trim().ToLower()) || search.CEQRNumber == null)
where (PACTable.ProjectName.ToLower().Contains(search.ProjectName.Trim().ToLower()) || search.ProjectName == null)
where (PATable.IsActive == true)
where (UserTable.IsActive == true)
select new
{
AssignmentID = PATable.AssignmentID,
UserID = PATable.UserID,
FirstName = UserTable.FirstName,
MiddleName = UserTable.MiddleName ?? string.Empty,
LastName = UserTable.LastName,
UserRole = UserRoleTable.UserRoleName,
CEQRNumber = PACTable.CEQRNumber,
ProjectName = PACTable.ProjectName,
CollectionID = PACTable.CollectionID,
EmailAddress = UserTable.EmailAddress,
AssignmentIsActive = PACTable.IsActive
};
答案 0 :(得分:1)
问题是您无法在right joins
中linq
执行此操作。好消息是您可以重写查询以避免使用right join
。您可以通过重新排列表格并使用left joins
来实现此目的。
目前你正在这样做:
select ...
from [MainTable] m
inner join [InnerTable] i on m.Num = i.Num
right join [RightTable] r on m.Num = r.Num
left join [LeftTable] l on r.Num = l.Num
这应该等同于:
select...
from [RightTable] r
left join [LeftTable] l on r.Num = l.Num
left join [MainTable] m on m.Num = r.Num
left join [InnerTable] i on m.Num = i.Num
现在您的查询没有right joins
,您应该可以编写linq查询