在LINQ to Entities中使用左外连接聚合函数

时间:2010-02-12 18:47:45

标签: linq linq-to-sql linq-to-entities aggregate left-join

我一直在寻找相关的LINQ问题,试图解决这个问题,但是我在将我的SQL查询转换为等效的LINQ to Entities版本时遇到了一些麻烦。

select companies.CommpanyName,
       job.Position,
       count(offers.jobID) As Offered,
       job.Openings,
       job.Filled
from jobs
left outer join offers on  jobs.ID = offers.JobID
join membership.dbo.individuals on jobs.UserID = individuals.ID
join membership.dbo.companies on individuals.CompanyID = companies.ID
where jobs.Hidden = 0
group by offers.JobID,
         companies.CommpanyName,
         job.Position,
         job.Openings,
         job.Filled

我在similar to this example之前在LINQ中完成了左外连接,但我不确定如何将countgroup语句与此结合以获得所需的结果:

    CompanyName    Position    Offered    Openings    Filled

1   Exmaple Co.    Job X       0          2           0
2   Example Co.    Job Y       4          6           3
3   Test Co.       Job Z       1          1           1

由于需要利用两个独立的数据上下文,查询变得更加复杂。我为缺乏示例代码道歉,但我真的不知道如何开始这个,我的LINQ-fu仍然很弱。

更新

这是我在Craig的帮助下得到的解决方案,因为不幸的多个上下文设置而不得不使用LINQ to Objects,JobWithOfferCounts不是实体对象:

IEnumerable<Job> t = context1.JobSet.Include("Offers").Include("Contacts").Where(j => j.Hidden == false);
IEnumerable <JobWithOfferCounts> r = (from j in t
                 join i in context2.IndividualSet on j.UserID equals i.ID
                 join c in context2.CompanySet on i.CompanyID equals c.ID
                 select new JobWithOfferCounts()
                 {
                    JobObject = j,
                    CompanyID = Convert.ToInt32(c.ID),
                    CompanyName = c.HostName,
                    OfferCount = j.offers.Count(o => o.Rejected == false),
                    FilledCount = j.offers.Count(o => o.Accepted == true),
                    PendingCount = j.offers.Count(o => o.Accepted == false && o.Rejected == false)
                 });            

        return r;

1 个答案:

答案 0 :(得分:2)

我看不出为什么你的查询中有individuals,或者为什么group by offers.JobID当它(不像jobs.JobId)可能为空时,但这是第一次刺:

var q = from c in Context.Companies     
        from i in c.Individuals
        from j in i.Jobs
        where j.Hidden == 0
        select new 
        {
            CompanyName = c.CompanyName,
            Position = j.Position,
            Offered = j.Offers.Count(),
            Openings = j.Openings,
            Filled = j.Filled
        };

It's rarely correct to use join in LINQ to Entities or LINQ to SQL