【问题标题】:Linq To SQL JoinLinq 到 SQL 连接
【发布时间】:2015-11-07 00:50:12
【问题描述】:

我正在学习 Linq2SQL,我有一个关于左外连接的问题。 在下面的示例中,我相信我正在对问题表执行左外连接到喜爱问题表。但是我不相信我的 where 子句是正确的。 因此,如果我对两个表执行左连接,我应该如何正确设置 where 子句?

var myResults = from quest in context.MyQuestions
                join favQuest in context.MyFavoriteQuestions on quest.UserFavoriteQuestionId equals favQuest.UserFavoriteQuestionId
                join specialQuest in context.Questions on favQuest.QuestionId equals specialQuest.QuestionId into joinedQuestions
                from specialQuest in joinedQuestions.DefaultIfEmpty()
                where (quest.UserId == userId) &&
                                    ( specialQuest.Id == paramId && (!specialQuest.IsBlue || (specialQuest.IsBlue && canViewBlueQuestion)) &&
                                      (!specialQuest.IsRed || (specialQuest.IsRed && canViewRedQuestion))
                                    )
                              select quest;

【问题讨论】:

  • LinqToSql 已被实体框架取代...您应该考虑改用它。
  • 对于不需要 EF 带来的臃肿的项目,LINQ2SQL 没有任何问题。
  • @Belogix - 您建议更换为运行速度较慢且不提供足够灵活性的工具
  • @Hogan 当然取决于您的需求!但是刚开始,已经退役的东西?评论不是开始辩论的好地方,但不确定你的论点是否成立(不再)。

标签: c# linq linq-to-sql


【解决方案1】:

对于 LINQ to SQL 上下文,建议这样编写左外连接,因为这实际上会生成一个 SQL 左连接:

var myResults = from question in context.MyQuestions
from favoriteQuestion in context.MyFavoriteQuestions
    .Where(fc => fc.UserFavoriteQuestionId == question.UserFavoriteQuestionId)
    .DefaultIfEmpty()

还建议(以提高可读性)将不相关的(和ANDed)where 子句分开:

var myResults = from question in context.MyQuestions
                where question.UserId == userId
                from favoriteQuestion in context.MyFavoriteQuestions
                    .Where(fc => fc.UserFavoriteQuestionId == question.UserFavoriteQuestionId)
                    .DefaultIfEmpty()
                from specialQuestion in context.Questions
                    .Where(sc => sc.QuestionId == favoriteQuestion.QuestionId)
                    .DefaultIfEmpty()
                where specialQuestion.Id == paramId
                where !specialQuestion.IsBlue || (specialQuestion.IsBlue && canViewBlueQuestion)
                where !specialQuestion.IsRed || (specialQuestion.IsRed && canViewRedQuestion)
                select question;

【讨论】:

  • 谢谢,这将有助于理解如何构建更好的查询。
猜你喜欢
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多