使用LINQ连接多个表

时间:2016-07-08 20:07:39

标签: c# linq asp.net-mvc-4 join

我想在SPID的主键上加入这3个表。

picture Table
[PIC_ID]   INT             
[pic_name] VARCHAR     
[SPID]     INT        
[pic]      VARBINARY (MAX)

service_provider table
[SPID]           INT           
[Sp_email]       VARCHAR 
[Sp_password]    VARCHAR 
[Sp_name]        VARCHAR   
[Sp_location]    VARCHAR 
[City_ID]        INT

city Table
[City_ID]  INT         
[Cityname] VARCHAR    

要在SPID上加入上表,我已在下面写了查询。

var sp_details = (from s in db.service_provider
                              join p in db.pictures on s.SPID equals p.SPID 
                              join c in db.cities on s.City_ID equals c.City_ID
                              where s.SPID == id
                              select new ImageData()
                              {
                                  SPID = s.SPID,
                                  Sp_name = s.Sp_name,
                                  Sp_location = s.Sp_location,
                                  Cityname = c.Cityname,
                                  service_type = s.service_type,
                                  Sp_description = s.Sp_description,
                                  Sp_rate = s.Sp_rate,
                                  Sp_web = s.Sp_web,
                                  Cnt_wh = s.Cnt_wh,
                                  pic = p.pic
                              });

在我的情况下,图片表不包含实例的值。那么如何使用相同的代码避免与其他表连接图片表并将sp_details返回到没有pic的VIEW。我很感激如果有人能帮助我解决这个问题。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,即使他们没有图像,你也想获得元素,所以你应该使用正确的联接,它应该返回来自联接的右边部分的所有行,即使他们没有& #39; t有图像。

var sp_details = (from s in db.service_provider
                              right join p in db.pictures on s.SPID equals p.SPID 
                              join c in db.cities on s.City_ID equals c.City_ID
                              where s.SPID == id
                              select new ImageData()
                              {
                                  SPID = s.SPID,
                                  Sp_name = s.Sp_name,
                                  Sp_location = s.Sp_location,
                                  Cityname = c.Cityname,
                                  service_type = s.service_type,
                                  Sp_description = s.Sp_description,
                                  Sp_rate = s.Sp_rate,
                                  Sp_web = s.Sp_web,
                                  Cnt_wh = s.Cnt_wh,
                                  pic = p.pic
                              });
相关问题