Linq used in Left Join

  Prepare some test data as follows:

 

 
   
use Test
Create table Student(
ID
int identity ( 1 , 1 ) primary key ,
[ Name ] nvarchar ( 50 ) not null
)

Create Table Book(
ID
int identity ( 1 , 1 ) primary key ,
[ Name ] nvarchar ( 50 ) not null ,
StudentID
int not null ) INSERT INTO Student values ( ' John Doe ' ) INSERT INTO Student values ( ' John Doe ' ) INSERT INTO Student values ( ' Wang Wu ' ) the SELECT * from Student - Joe Smith borrowed books INSERT INTO Book values ( ' Red House ' , . 1 ) INSERT INTO Book values (









' Westward Red House ' , 1 )

- John Doe borrow books INSERT INTO Book values ( ' Three ' , 2 ) - king five did not borrow - a false record INSERT INTO Book values ( ' How to excel error a ' , 111 ) - left connecting SELECT s.name, b.name from Student AS S left the Join Book AS B ON s.id = b.studentid -











右连接
select s.name,b.name from student as s
right join Book as b on s.id = b.studentid

 

Use Linq to achieve left connected, worded as follows

 

 
   
DB DataClasses1DataContext = new new DataClasses1DataContext (); var leftJoinSql = from Student in db.Student the Join Book in db.Book ON student.ID the equals book.StudentID INTO TEMP from TT in temp.DefaultIfEmpty () SELECT new new { sname = student.Name, bname = tt == null ? "" : tt.Name // this is mainly the second set there may be empty. Analyzing need };







 

 

 

 

Linq implemented with the right connection, the following wording

 

 

 
   
DataClasses1DataContext db = new DataClasses1DataContext();
var rightJoinSql
= from book in db.Book
join stu
in db.Student on book.StudentID equals stu.ID into joinTemp
from tmp
in joinTemp.DefaultIfEmpty()
select
new {
sname
= tmp == null ? "" :tmp.Name,
bname
= book.Name

};

 

 

Reference: http: //developer.51cto.com/art/200909/152189.htm

http://hi.baidu.com/thinsoft/blog/item/83fb1e9089cc7186a877a4b1.html

http://apps.hi.baidu.com/share/detail/12540006

http://www.winu.cn/space-14160-do-blog-id-25172.html

Reproduced in: https: //www.cnblogs.com/xinjian/archive/2010/11/17/1879959.html

Guess you like

Origin blog.csdn.net/weixin_33788244/article/details/93822267
Recommended