使用Entity Framework将子查询表连接到表函数,外部应用

时间:2016-01-19 17:59:07

标签: sql-server entity-framework linq outer-apply

我创建了一个SQL Server查询,通过获取一个不同的case id列表并将它们连接到fnGetRelatedCases表函数来获得正确的结果。但是,我无法创建执行相同操作的实体框架查询。

SQL Server:

 select 
     cse.*
 from 
     (select distinct 
          CaseID
      from 
          ELFJuv.fnGetCalendar()
      where 
          Department = @Department 
          and HearingDateOnly = @FilterDate) as C
 outer apply 
     ELFJuv.fnGetRelatedCases(C.CaseID) as CSE
 where 
     CSE.CaseID is not null

下面的查询几乎可以正常工作,但它不会通过不同的案例ID列表加入。

实体框架:

IEnumerable<fnGetRelatedCases_Result> cases = 
(from calendar
 in _ctx.fnGetCalendar()
 where calendar.Department.Equals(department) &&
 calendar.HearingDateOnly == filterDate
 from fullCaseDetail in _ctx.fnGetRelatedCases(calendar.CaseID)
 select fullCaseDetail).ToList();

我需要将一个不同的case id列表传递给fnGetRelatedCases表函数,但由于所有case id都被连接,我无法正确连接。

2 个答案:

答案 0 :(得分:0)

我想出了如何解决问题。

(from calendar in _ctx.fnGetCalendar()
.Where(d => d.HearingDateOnly == filterDate && d.Department == department)
.Select(x => new { x.CaseID })
.Distinct()
from fullCaseDetail in _ctx.fnGetRelatedCases(calendar.CaseID)
select fullCaseDetail).ToList();

答案 1 :(得分:0)

你去吧

var cases = 
   (from caseID in (from calendar in _ctx.fnGetCalendar()
               where calendar.Department.Equals(department)
                   && calendar.HearingDateOnly == filterDate
               select calendar.CaseID).Distinct()
    from fullCaseDetail in _ctx.fnGetRelatedCases(caseID)
    select fullCaseDetail).ToList();

相当于

// Subquery
var subquery =
    (from caseID in (from calendar in _ctx.fnGetCalendar()
     where calendar.Department.Equals(department)
         && calendar.HearingDateOnly == filterDate
         select calendar.CaseID).Distinct();
// Query
var query = 
    from caseID in subquery
    from fullCaseDetail in _ctx.fnGetRelatedCases(caseID)
    select fullCaseDetail;
// Result
var cases = query.ToList();