我会尽量简而言之:我是LINQ的新手。在那里。
我有三个表,已将EntityFramework集成到我的解决方案中:
Employees Desks Rooms
-------------- ------------ ------------
FirstName DeskId RoomId
DeskId RoomId RoomName
Color HasWindows
Width
我需要查看:
Employee Room name
----------------------------------
Lumberg Corner Office
Milton Storage in basement
Peter Cubicle 214
因此,我创建了一个EmployeeRoomListViewModel
,并在LINQ中使用JOINs
进行了填充。除无汗外
我缺少一些记录。即那些没有分配办公桌的员工(DeskId
为空)。我也需要那些。
这是我的LINQ:
from Emp in db.Employees
join D in db.Desks on D.DeskId equals Emp.DeksId
join R in db.Rooms on D.RoomId equals R.RoomId
select new EmployeeRoomListViewModel
{
Employee = Emp.FirstName,
Room = R.RoomName
}).ToList();
有什么想法吗?
答案 0 :(得分:2)
您的查询是正确的,但您只需要在其中添加“ Into Alias”和DefaultIfEmpty()。
from Emp in db.Employees
join Des in db.Desks on Des.DeskId equals Emp.DeksId into SomeThing
from Des in SomeThing.DefaultIfEmpty();
答案 1 :(得分:0)
您需要对左外部联接使用DefaultIfEmpty子句
from Emp in db.Employees
join D in db.Desks on D.DeskId equals Emp.DeksId into employeeDesks
from ed in employeeDesks.DefaultIfEmpty()
join R in db.Rooms on D.RoomId equals R.RoomId into deskRooms
from dr in deskRooms.DefaultIfEmpty()
select new EmployeeRoomListViewModel
{
Employee = Emp.FirstName,
Room = R.RoomName
}).ToList();
答案 2 :(得分:0)
这将解决您的问题
from Emp in db.Employees
join D in db.Desks on D.DeskId equals Emp.DeksId into desklist from deskjoin in
desklist.DefaultIfEmpty()
join R in db.Rooms on deskjoin.RoomId equals R.RoomId into roomlist from roomjoin in roomlist.DefaultIfEmpty() select new EmployeeRoomListViewModel
{
Employee = Emp.FirstName,
Room = roomjoin.RoomName
}).ToList();
第一次需要将左连接雇员表和Desks表一起使用,然后需要左雇员的雇员和Desk表联接的结果
在此“从desklist中的deskjoin中进入桌面列表中。DefaultIfEmpty()”用于左联接查询