linq連接查詢從第二個表獲得單個記錄。

[英]linq join query get single record from second table


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 .

我正在使用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  

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

2 个解决方案

#1


4  

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

#2


1  

Your can write subquery here:

你可以在這里寫子查詢:

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

or if there is chance that in Images table no row matches then you need to work around this way to prevent Null Reference Exeption:

或者如果有可能在圖像表中沒有行匹配,那么您需要使用這種方法來防止空引用調用:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/04/26/d2876ccc95ca21428b5154b56985641b.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com