有兩張表:
專業表:
學生表:
學生表中外鍵約束mno是專業表的主鍵
EfCore中有兩種連接查詢:
Lambda表達式的Join:
public async Task<dynamic> GetStudentDataLambdaAsync() { //Join<TOuter, TInner, TKey, TResult> var res = _appDbContext.Major.Join(_appDbContext.Student, a => a.mno, g => g.mno, (a, g) => new { a.mno, a.manme, g.sno, sex = g.sex == true ? "男" : "女", g.sname }); return res; }
Linq的Join:
注意引用:using System.Linq;
public async Task<dynamic> GetStudentDataLinqAsync() { var res = from m in _appDbContext.Major join s in _appDbContext.Student on m.mno equals s.mno into r from a in r.DefaultIfEmpty() select new { a.sno, a.sname, sex = a.sex == true ? "男" : "女", a.mno, m.manme, }; return res; }
結果: