在LINQ中插入附加条件

时间:2019-01-30 03:14:46

标签: sql-server linq

我正在SQL Server 2014中修改LINQ查询,但是我从未使用过语法:

if (!UserAccessMatrixSession.HasRole(Session, Constant.ROLE_STAFF))
{
    if (country != 0 )
    {
        ViewData["Employees"] = (from staff in db.Staffs
                                 from jobinfo in db.JobInfo
                                        .Where(x => x.staff_id == staff.StaffID)
                                        .OrderByDescending(x => x.jobinfo_id).Take(1)
                                 orderby staff.Alias
                                 select new { staff, jobinfo }).Where(x => x.jobinfo.location == country)
                                 .Select(x => x.staff).ToList();
    }
    else
    {
        ViewData["Employees"] = (from staff in db.Staffs
                                 orderby staff.Alias
                                 select staff).ToList();
    }
}

我想插入一个附加条件,如下:

where jobinfo.last_date == null OR DateTime.Now < jobinfo.last_date

1 个答案:

答案 0 :(得分:0)

我相信您希望将where子句添加到要从职位信息中选择的位置

if (!UserAccessMatrixSession.HasRole(Session, Constant.ROLE_STAFF))
{
    if (country != 0 )
    {
        ViewData["Employees"] = (from staff in db.Staffs
                                 from jobinfo in db.JobInfo
                                        .Where(x => x.staff_id == staff.StaffID)
                                        .OrderByDescending(x => x.jobinfo_id).Take(1)
                                 orderby staff.Alias
                                 select new { staff, jobinfo }).Where(x => x.jobinfo.location == country 
                             /* last_date null or UtcNow < last_date*/ && (x.jobinfo.last_date == null || DateTime.UtcNow < jobinfo.last_date))
                                 .Select(x => x.staff).ToList();
    }
    else
    {
        ViewData["Employees"] = (from staff in db.Staffs
                                 orderby staff.Alias
                                 select staff).ToList();
    }
}