EFCore中Linq与Lambda的左连接查询

有两张表:

专业表:

 

学生表:

 

 

 学生表中外键约束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;
        }

结果:

 

posted @ 2022-04-19 14:22  点终将连成线  阅读(897)  评论(0编辑  收藏  举报