linq join查询从第二个表中获取单个记录 [英] linq join query get single record from second table

查看:56
本文介绍了linq join查询从第二个表中获取单个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用linq join从两个表中获取数据.但是我的第二个表有多个记录对应于第一个表.而且我只想从第二张表中获得第一条记录.

I am using linq join to get data from two tables. But my second table has multiple records corresponding to first table. And i want only first record from second table .

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  

我正在使用以下代码.及其返回的四个记录.

I am using the following code. and its returning four records.

 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>();
        }

推荐答案

...
join r in context.images
on p.id equals r.studentId into imgs
from r in imgs.Take(1)
...

这篇关于linq join查询从第二个表中获取单个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆