【问题标题】:Convert SQL query with join to lambda expression将带有连接的 SQL 查询转换为 lambda 表达式
【发布时间】:2014-04-09 02:21:23
【问题描述】:

不确定如何将以下 sql 转换为 lambda 表达式。我的数据库以一对多的关系使用与表 Content_Training 相关的参照完整性和表 Content(1 个内容可以有多个 content_training)

select c.ContentId, c.Name, ct.TrainingTypeId 
from dbo.Content c left join dbo.Content_Training ct on c.ContentId = ct.ContentId
where c.PublishDate is not null
order by ct.TrainingTypeId, c.Name

【问题讨论】:

    标签: c# sql entity-framework linq-to-entities sql-to-linq-conversion


    【解决方案1】:

    试试这个查询:

    var results = (from c in dbcontext.Contents
                   join ct in dbcontext.Content_Trainings on c.ContentId equals ct.ContentId into t
                   from rt in t.DefaultIfEmpty()
                   select new
                   {
                       c.ContentId,
                       c.Name,
                       TrainingTypeId = (int?)rt.TrainingTypeId
                   }).OrderBy(r => r.TrainingTypeId)
                     .ThenBy(r => r.Name);
    

    【讨论】:

    • 我会不断使用查询语法,不使用 lambda,即orderby x,y。它会更具可读性。
    • 感谢 Abatishchev。在过去,我使用了“let”关键字,而不是您使用的“into t ... t.DefaultIfEmpty()”。有什么区别?
    猜你喜欢
    • 1970-01-01
    • 2020-07-15
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多