ap.*_*ngh 3 c# linq sql-server
我正在使用linq join从两个表中获取数据。但是我的第二个表有多个记录对应于第一个表。而且我只希望第二张桌子有第一条记录。
Table student
id name
1 a1
2 b1
Table images
id image studentId
1 1.jpg 1
2 2.jpg 1
3 3.jpg 2
4 4.jpg 2
Result should be
id name image
1 a1 1.jpg
2 b1 3.jpg
Run Code Online (Sandbox Code Playgroud)
我正在使用以下代码。及其返回的四个记录。
public IEnumerable<StudentBean> getStudent()
{
return (from p in context.student
join r in context.images
on p.id equals r.studentId
select new StudentBean
{id=p.id,
name =p.name,
image=r.image
}).ToList<StudentBean>();
}
Run Code Online (Sandbox Code Playgroud)
小智 6
...
join r in context.images
on p.id equals r.studentId into imgs
from r in imgs.Take(1)
...
Run Code Online (Sandbox Code Playgroud)
您可以在这里编写子查询:
return (from p in context.student
select new StudentBean
{
id=p.id,
name =p.name,
image=(from r in context.images
where r.studentId == p.id
select r).First().image
}).ToList<StudentBean>();
Run Code Online (Sandbox Code Playgroud)
或者,如果图像表中没有行匹配,那么您需要解决此问题以防止空引用异常:
return (from p in context.student
let Image = (from r in context.images
where r.studentId == p.id
select r).FirstOrDefault()
select new StudentBean
{
id=p.id,
name = p.name,
image = Image != null ? Image.image : null
}).ToList<StudentBean>();
Run Code Online (Sandbox Code Playgroud)