2012-04-05 61 views
2

我在我的数据库中有两个表,看起来就像是:如何在Linq中获得左外连接?

客户:

C_ID city 
-------------- 
1  Dhaka 
2  New york 
3  London 

的personal_info:

P_ID C_ID Field  value 
------------------------------- 
1  1  First Name Nasir 
2  1  Last Name Uddin 
3  2  First Name Jon 
4  3  First Name Lee 


我需要一个选择的结果类似:

C_ID ='1':

C_ID = '2':

C_ID Name (First Name + Last Name) City 
--------------------------------------------- 
2  Jon       New york 

如何将相应的Linq查询是什么样子?

感谢
Nahid

+0

请参见http://stackoverflow.com/questions/1122942/linq-to-sql-left-outer-join-with-multiple-join-conditions的答案 – 2012-04-05 09:27:24

+4

经过将近50个问题你应该开始使用编辑器中的代码块按钮。 – 2012-04-05 09:27:59

回答

3

继以前的答案,如Linq to Sql: Multiple left outer joins你可以看到结构解决这一比如像:

var result = from customer in customers 
        from personalFirst in personal 
         .Where(pf => pf.Field == "First Name" && pf.C_ID == customer.C_ID) 
         .DefaultIfEmpty() 
        from personalLast in personal 
         .Where(pl => pl.Field == "Last Name" && pl.C_ID == customer.C_ID) 
         .DefaultIfEmpty() 
        where customer.C_ID == 2 
        select new { customer.C_ID, Name = (personalFirst != null ? personalFirst.Value : "") + " " + (personalLast != null ? personalLast.Value : "") }; 

显然,如果你想要的所有记录,然后卸下C_ID限制= 2

+0

感谢回答。它的工作.... – Nasir 2012-04-05 10:41:51

+2

请downvoter请解释为什么?因此LINQ的作品可以回答这个问题。如果有更好的方法(可能会有),那么它的价值就会显现出来 – kaj 2012-04-05 10:48:54