Linq在多个表格上按年份获取历史记录详细信息

时间:2013-07-30 09:13:28

标签: sql database linq linq-to-entities

在我的应用程序中,我想显示给定用户的历史记录详细信息。用户可以拥有许多工作,并可以访问具有不同角色的不同促销。

我希望能够展示这种历史

位置促销

2012助理 促销2012

2013管理器 促销2013

我尝试了这个查询(我正在使用Linq实体)

var query = (from u in context.Users
             join j in context.Jobs.Where(jo => jo.JobStartDate.HasValue) on u.UserID equals j.UserID into jobs
             from job in jobs.DefaultIfEmpty()
             join uir in context.UserInRoles on u.UserID equals uir.UserID into userInRoles
             from userInRole in userInRoles.DefaultIfEmpty()
             join rip in context.RoleInPromotion on userInRole.RoleInPromotionID equals rip.RoleInPromotionID into roleInPromotions
             from roleInPromotion in roleInPromotions.DefaultIfEmpty()
             join p in context.Promotions.Where(pro => pro.PromotionStartDate.HasValue) on roleInPromotion.PromotionID equals p.PopulationTargetID into promotions
             from promo in promotions.DefaultIfEmpty()
             where u.UserID == userId 
             select new
             {
                 Year = job.JobStartDate.HasValue ? job.JobStartDate.Value.Year : promo.PromotionStartDate.HasValue ? promo.PromotionStartDate.Value.Year : 0,
                 JobTitle = job.JobTitle,
                 Promotion = promo.PromotionName
             }).Distinct().ToList();

但是这给了我这个结果,即使用户在2012年无法访问任何促销活动

位置促销

2012助理 促销2013

2013管理器 促销2013

我也试过了,但它似乎没有改变任何东西

group new { job, promo } by new { jobYear = job.JobStartDate.Value.Year, promoYear = promo.PromotionStartDate.Value.Year } into grp

1 个答案:

答案 0 :(得分:0)

你试试这个:

var query = (from u in context.Users
             join j in context.Jobs.Where(jo => jo.JobStartDate.HasValue) on u.UserID equals j.UserID into jobs
             from job in jobs.DefaultIfEmpty()
             join uir in context.UserInRoles on u.UserID equals uir.UserID into userInRoles
             from userInRole in userInRoles.DefaultIfEmpty()
             join rip in context.RoleInPromotion on userInRole.RoleInPromotionID equals rip.RoleInPromotionID into roleInPromotions
             from roleInPromotion in roleInPromotions.DefaultIfEmpty()
             join p in context.Promotions.Where(pro => pro.PromotionStartDate.HasValue) on roleInPromotion.PromotionID equals p.PopulationTargetID into promotions
             from promo in promotions.DefaultIfEmpty()
             where u.UserID == userId 
         let year=job.JobStartDate.HasValue ? job.JobStartDate.Value.Year : promo.PromotionStartDate.HasValue ? promo.PromotionStartDate.Value.Year : 0
             select new
             {
                 Year =year ,
                 JobTitle = job.JobTitle,
                 Promotion = "Promotion "+year
             }).Distinct().ToList();