将此SQL转换为链接Left Outer Join和Case语句

时间:2015-09-08 22:53:13

标签: linq

我在将此sql语句转换为Linq时遇到问题。它有一个Left outer join和case语句。我将尝试下面给出的答案。

SELECT  [job_required_document].[job_required_document_id]
  ,[document_name]
  ,[document_description]
     ,CASE WHEN dlink.job_required_document_id is NULL THEN 0 ELSE 1  END    AS DocIsRequired
  FROM [dbo].[job_required_document]
          LEFT OUTER JOIN [dbo].[job_description_document_link] dlink ON      job_required_document.job_required_document_id =     dlink.job_required_document_id 
                 AND dlink.job_description_id = @JobDescriptionId

**这就是我所做的。但docIsRequired对所有记录来说都是1。我认为案例陈述是错误的。

             var query = from document in context.job_required_documents

                    join dlink in context.job_description_document_links.Where(q => q.job_description_id == job_description_id && q.job_description_id == job_description_id)
                    on document.job_required_document_id equals dlink.job_required_document_id into documentdlink

                    from q in documentdlink.DefaultIfEmpty()

                    select new Documents
                    {
                        job_description_id = job_description_id,
                        job_required_document_id = document.job_required_document_id,
                        document_name = document.document_name,
                        document_description = document.document_description,
                        docIsRequired = document.job_required_document_id == null ? 0 : 1
                    };

1 个答案:

答案 0 :(得分:0)

创建一个包含以下详细信息的自定义类:

public class DocumentDetails
{
 public int docID {get;set;}
 public string docName {get;set;}
 public string docDesc {get;set;}
 public int docIsRequired {get;set;}
}

现在使用此LINQ将数据提取到此类类型的集合中,如下所述:

  List<DocumentDetails> documentDetialsList = (from document in  datacontext.job_required_document
    from dlink in datacontext.job_description_document_link 
    .where(x=> x.job_required_document_id ==  document.job_required_document_id).DefaultIfEmpty()
     where dlink.job_description_id == @JobDescriptionId
     select new {
        docID = document.[job_required_document_id], 
        docName = document.[document_name], 
        docDesc = document.[document_description],
        docIsRequired = dlink.job_required_document_id == null ? 0 : 1
       }).ToList();

希望这会有所帮助......