我正在尝试将SQL查询转换为LINQ,但经过多次尝试后,我仍然不在那里......有人可以帮忙吗?
这是我正在使用的SQL语句
SELECT Users.email, SUM(Skills.level) AS SkillLevel
FROM Skills INNER JOIN
SkillsPerUser ON Skills.pk_skill_id = SkillsPerUser.fk_skill_id INNER JOIN
Users ON SkillsPerUser.fk_user_id = Users.pk_userid
GROUP BY Users.email
ORDER BY SkillLevel DESC
这是我到目前为止所提出的,但它缺少一个sum(),其中我硬编码数字3,应该是Skills.level的总和:
var allSkillsPerUser = from u in dc.Users
join spu in dc.SkillsPerUsers on u.pk_userid equals spu.fk_user_id
join s in dc.Skills on spu.fk_skill_id equals s.pk_skill_id
select new { Email = u.email, Level = s.level } into su
group su by su.Email into gsu
select new { Email = gsu.Key, SkillLevel = gsu.Sum(su => su.Level) };
ViewBag.spu = allSkillsPerUser.ToList();
视图包出现以下错误(无法找到电子邮件,而在下面的变量中,您可以看到它们确实存在...):
感谢您帮助我!
答案 0 :(得分:1)
context.Skills
.Join(context.SkillsPerUser, s => s.pk_skill_id, spu => spu.fk_skill_id, (s, spu) => new { Skill = s, SkillToUser = spu })
.Join(context.Users, sspu => sspu.SkillToUser.fk_userId, u => u.pk_userid, (sspu, u) => new { Email = u.Email, SkillLevel = sspu.Skill.level })
.GroupBy(su => su.Email)
.Select(g => new { Email = g.Key, SkillLevel= g.Sum(su => su.Level) })
.OrderByDescending(g => g.SkillLevel)
如果您在实体上设置了导航属性,则会更简单一些:
context.SkillsPerUser
.Select(spu => new { Email = spu.User.email, Level = spu.Skill.level }) // guessing at the navigation property names here
.GroupBy(su => su.Email)
.Select(g => new { Email = g.Key, SkillLevel = g.Sum(su => su.Level) })
.OrderByDescending(g => g.SkillLevel)
或者,使用查询语法
from u in dc.Users
join spu in dc.SkillsPerUsers on u.pk_userid equals spu.fk_user_id
join s in dc.Skills on spu.fk_skill_id equals s.pk_skill_id
select new { Email = u.email, Level = s.level } into su
group su by su.Email into gsu
select new { Email = gsu.Key, SkillLevel = gsu.Sum(su => su.Level) }
要按总额订购,您可以这样做:
from u in dc.Users
join spu in dc.SkillsPerUsers on u.pk_userid equals spu.fk_user_id
join s in dc.Skills on spu.fk_skill_id equals s.pk_skill_id
select new { Email = u.email, Level = s.level } into su
group su by su.Email into gsu
select new { Email = gsu.Key, SkillLevel = gsu.Sum(su => su.Level) } into userSkills
orderby userSkills.SkillLevel descending