因此,我们有两个表:
CARS
ID CAR_MODEL
11 Mustang
22 Camaro
33 F-150
PARTS
ID CAR_ID PART_NAME
1 11 Steering Wheel
2 22 Steering Wheel
3 22 Headlights
注意:PARTS.CAR_ID
和CARS.ID
列之间的数据库中没有外键关系。
没有外键,将使用哪种linq查询来获得这些结果:
CARS
ID CAR_MODEL PART_NAME_LIST
11 Mustang Steering Wheel
22 Camaro Steering Wheel, Headlights
33 F-150 (null)
环境:SQL Server 2014,linq-to-sql
编辑:这是我到目前为止的内容,但这在结果中导致4行(Camaro为2行),而不是3行,并且不包含任何部分。
from C in db.CARS
join P in db.PARTS on C.ID equals P.CAR_ID
select new{
ID = C.ID,
CAR_MODEL = C.CAR_MODEL,
PART_NAME_LIST = ???
}
答案 0 :(得分:1)
要连接字符串,必须使用string.Join
。最简单的方法是在子查询中:
(
from c in db.CARS
select new
{
ID = c.ID,
CAR_MODEL = c.CAR_MODEL,
PART_NAME_LIST = db.PARTS
.Where(p => c.ID equals p.CAR_ID)
.Select(p => p.PART_NAME)
}
).AsEnumerable()
.Select(c => new
{
ID = c.ID,
CAR_MODEL = c.CAR_MODEL,
PART_NAME_LIST = string.Join(", ", cPART_NAME_LIST)
})
实体框架不支持string.Join
,因此您必须将查询分为EF可以转换为SQL的部分和在内存中执行的部分,以AsEnumerable()
分隔。
答案 1 :(得分:1)
这是流利的语法组联接:
var sub = (from C in db.CARS
join P in db.PARTS on C.ID equals P.CAR_ID into Pj
select new {
C.ID,
C.CAR_MODEL,
PART_NAMES = from p in Pj select p.PART_NAME
})
.AsEnumerable();
var ans = from icp in sub
select new {
icp.ID,
icp.CAR_MODEL,
PART_NAME_LIST = String.Join(", ", icp.PART_NAMES)
我可能会在代码中的select
中使用lambda语法:
var ans = (from C in db.CARS
join P in db.PARTS on C.ID equals P.CAR_ID into Pj
select new {
C.ID,
C.CAR_MODEL,
PART_NAMES = Pj.Select(cpj => cpj.PART_NAME)
})
.AsEnumerable()
.Select(icp => new {
icp.ID,
icp.CAR_MODEL,
PART_NAME_LIST = String.Join(", ", icp.PART_NAMES)
});