如何转换sql查询添加和连接到linq

时间:2010-12-20 20:33:08

标签: sql linq

我有一个工作的SQL查询,我一直试图在过去几天转换为linq。我已经在这里和各种网站上阅读了几篇帖子,但是在尝试将其转换为有效的linq查询时,我没有成功。

我特别遇到处理数学问题的部分(添加单个分数以获得total_score值)并从Schools表中获取值,以便我可以将它们传递给我的视图。

这是sql查询:

SELECT bowler_name, school_name, bowler_gm1, bowler_gm2, bowler_gm3, bowler_gm4, bowler_gm5, bowler_gm6, (ISNULL([bowler_gm1],0)+ISNULL([bowler_gm2],0)+ISNULL([bowler_gm3],0)+ISNULL([bowler_gm4],0)+ISNULL([bowler_gm5],0)+ISNULL([bowler_gm6],0)) AS total_score 
FROM Bowlers 
JOIN Schools ON Schools.school_id = Bowlers.school_id 
ORDER BY total_score DESC;

在事情开始破坏之前,这是我用linq查询得到的:

from s in db.Schools
join b in db.Bowlers on s.school_id equals b.school_id
select b;

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

这样的事情可以帮助你。

from s in db.Schools
join b in db.Bowlers on s.school_id equals b.school_id
select new {
  bowler_name = b.bowler_name,
  ...
  totalscore = bowler_gm1 + bowler_gm2 + bowler_gm3 ...
};

请注意,如果您要创建一个BowlerGame表,那么处理空值会容易得多 GameID为PK,BowlerID为FK为投球手,GameNumber为游戏编号,最后得分为该游戏的得分