ef 三表join,三表left join
电脑版发表于:2019/10/21 9:38
EF三表join:
sql写法:
//sql List<UserScoreViewModel3> ulist = oae.Database.SqlQuery<UserScoreViewModel3>(@" select u.username,p.father,s.sub,s.score from dbo.Users u join dbo.User_Parent p on u.id = p.usersid oin dbo.Score s on u.id = s.usersid ").ToList();
linq写法:
//linq var query = from u in oae.Users join p in oae.User_Parent on u.Id equals p.UsersId join s in oae.Score on u.Id equals s.UsersId select new { username = u.UserName, father = p.Father, sub = s.Sub, score = s.Score1 }; var result = query.ToList();
lamdba写法:
//lamdba var query = oae.Users.Join(oae.User_Parent, a => a.Id, b => b.UsersId, (a, b) => new { user = a, parent = b }).Join(oae.Score, a => a.user.Id, b => b.UsersId, (a, b) => new { username = a.user.UserName, father = a.parent.Father, sub = b.Sub, score = b.Score1 }); var result = query.ToList();
EF三表left join:
linq写法:
var query = from u in oae.Users join p in oae.User_Parent on u.Id equals p.UsersId into jointemp from leftjoin in jointemp.DefaultIfEmpty() join s in oae.Score on u.Id equals s.UsersId into sjointemp from sleftjoin in sjointemp.DefaultIfEmpty() select new { username = u.UserName, father = leftjoin.Father, sub = sleftjoin.Sub, score = sleftjoin.Score1 }; var result = query.ToList();
lamdba写法1:
//三表 left join lamdba var result2 = oae.Users.GroupJoin(oae.User_Parent, a => a.Id, b => b.UsersId, (a, b) => new { uid = a.Id, username = a.UserName, parents = b }).SelectMany(a => a.parents.DefaultIfEmpty(), (a, b) => new { uid = a.uid, username = a.username, father = b.Father }).GroupJoin(oae.Score, a => a.uid, b => b.UsersId, (a, b) => new { username = a.username, father = a.father, scores = b }).SelectMany(a => a.scores.DefaultIfEmpty(), (a, b) => new { username = a.username, father = a.father, sub = b.Sub, score = b.Score1 }).ToList();
lamdba写法2:
//三表 left join lamdba写法2 var result3 = oae.Users.GroupJoin(oae.User_Parent, a => a.Id, b => b.UsersId, (a, b) => new { uid = a.Id, UserName = a.UserName, parents = b }).GroupJoin(oae.Score, a => a.uid, b => b.UsersId, (a, b) => new { UserName = a.UserName, parents = a.parents, scores = b }).SelectMany(a => a.scores.DefaultIfEmpty(), (a, b) => new { UserName = a.UserName, parents = a.parents, sub = b.Sub, score = b.Score1 }).SelectMany(a => a.parents.DefaultIfEmpty(), (a, b) => new { UserName = a.UserName, sub = a.sub, score = a.score, father = b.Father }); var resultList = result3.ToList();