我有三张桌子:房屋,人和人房屋分配
在我的Houses
- 表中,我得到了不同的列,例如HouseName
,HouseType
和Description
。
在PeopleHouseAssignments
我有PersonId
和HouseId
等列。
我现在想以下列方式在我的WPF DataGrid中显示它:
一个名为HouseNames
的列,其中包含Houses
- 表中所有可用的HouseNames。
我现在在我的数据网格中有一个复选框,应该将当前选定的人分配给房子。
[ ] House1
[x] House2
[ ] House3
[x] House4
此人被分配到House2和House4,因为表“PersonHouseAssignments”有两行:
PersonId | HouseId
1 | 2
1 | 4
我应该如何创建LINQ查询?
我已经尝试过类似的东西,但这不起作用:
from p in _dataContext.Houses
from a in _dataContext.PersonHouseAssignments
select new {HouseNames = p.HouseName, IsAssigned = a.HouseId == p.Id, Description = a.Description }
答案 0 :(得分:3)
您可以使用GroupJoin:
var query = from h in _dataContext.Houses
join a in _dataContext.PersonHouseAssignments
on h.Id equals a.HouseId into assignments
select new
{
HouseName = p.HouseName,
IsAssigned = assignments.Any(),
//..
}
答案 1 :(得分:3)
我认为您的查询将特定于某个人?也就是说,如果该特定人被分配到名为IsAssigned
的房屋,则返回集合中每个项目的true
值将为HouseName
?在这种情况下,您可以使用嵌套的子查询:
int personId = 1;
var query =
from h in _dataContext.Houses
select new
{
HouseName = h.HouseName,
IsAssigned =
(
from a in _dataContext.PersonHouseAssignments
where a.HouseId == h.Id && a.PersonId == personId
select a
).Any()
};
修改:如果您希望加入Description
中的PersonHouseAssignments
,可以使用:
int personId = 1;
var query =
from h in _dataContext.Houses
let a =
(
from pha in _dataContext.PersonHouseAssignments
where pha.HouseId == h.Id && pha.PersonId == personId
select pha
).FirstOrDefault()
select new
{
HouseName = h.HouseName,
Description = a != null ? a.Description : "",
IsAssigned = a != null
};
答案 2 :(得分:3)
var query = from house in _dataContext.Houses
join assignment in _dataContext.PersonHouseAssignments
on house.Id equals assignment.HouseId into results
from r in results.DefaultIfEmpty()
select new
{
HouseNames = house.HouseName,
IsAssigned = r != null,
Description = r != null ? r.Description : string.Empty
}
这将生成带有左外连接的SQL,以包含Description
。