在outter中加入LINQ到实体

时间:2015-12-27 13:53:36

标签: entity-framework linq

我使用Entity Framework-6。 我有这个代码(outter join,LINQ to entity):

        var inspectionSitesConjection = (from st in sites
                                         join ir in inspectionReview on st.Id equals ir.SiteId into g
                                         from subsite in g.DefaultIfEmpty()
                                         select new GeneralReportViewModel
                                         {
                                             siteName = subsite.Site.Name,
                                             address = subsite.Site.Description,
                                             inspectionDate = subsite.DateReview,
                                             siteType = subsite.Site.SiteType.Description,
                                             frequency = subsite.InspectionFrequency.Name,
                                             status = subsite.IsNormal,
                                         }).AsNoTracking();

我需要按siteNamefrequency分组。

在LINQ里面制作小组是不是很容易?

1 个答案:

答案 0 :(得分:1)

这是一个起点:

var grouped = inspectionSitesConjection
    .GroupBy(item => new { item.siteName, item.frequency });

但请注意,结果(正如您在Queryable.GroupBy文档中看到的)不再是IQueryable<GeneralReportViewModel>,而是IQueryable<IGrouping<Key, GeneralReportViewModel>>其中Key是具有siteName的匿名类型和frequency属性。

我提供这个只是因为你特别要求。你用这个查询想要实现的目标并不十分清楚。此外,一旦您决定使用显式连接,则使用联接表而不是导航属性,并考虑由于外连接subsite可以为null。

from st in sites
join ir in inspectionReview on st.Id equals ir.SiteId into g
from subsite in g.DefaultIfEmpty()
select new GeneralReportViewModel
{
    siteName = st.Name,
    address = st.Description,
    siteType = st.SiteType.Description,
    inspectionDate = subsite.DateReview, // problem if subsite == null
    frequency = subsite.InspectionFrequency.Name, // problem if subsite == null
    status = subsite.IsNormal, // problem if subsite == null
})