简体   繁体   English

无法在where子句中使用条件语句

[英]Not able to make use of the conditional statement in where clause

Here is my below code 这是我的下面的代码

string CampusId = "1";
string ClassId = "1";
var Class = GetClassesselect();
var model = (from sr in db.StudentRequests
join c in db.Classes
on sr.ClassId equals c.ClassId
where 
(CampusId ==""?"0": CampusId)
&& (ClassId == "" ? "0" : ClassId)
orderby sr.CreatedOn descending
select new Studentvm
{   
PaymentMethod = sr.PaymentMethod,
CampusId = (int)ViewData["CampusId"],
ClassId = (int)ViewData["ClassId"],
Availableclass = Class,   
})
.ToList().ToPagedList(page ?? 1, 10);


public IList<SelectListItem> GetClassesselect()
{
    // This comes from database.       
    var Class = db.Classes
        .Select(x => new SelectListItem { Text = x.ClassName, Value = x.ClassId.ToString() })
        .ToList();
    Class.Insert(0, new SelectListItem { Text = "--Please Select--", Value = "" });
    return Class;
}

Here I am trying to make where statement as conditional that if campusid is null then by default it does not count that where condition else where condition should be taken 在这里,我试图使where语句成为条件语句,如果Campusid为null,则默认情况下不计算条件,否则应采取条件

Example like In sql we are doing some thing as 像在sql中这样的示例

Select *
from Registration where     
(ISNULL(@CampusId,'')='' OR (R.CampusId = @CampusId ))
AND  (ISNULL(@ClassId,'')='' OR (TC.ClassId =@ClassId))

here in above sql if @CampusId is null then that statement will not be taken as granted in where condition 在上面的sql中,如果@CampusId为null,则在where条件下该语句将不被视为已授予

So I am trying to do same thing in above Linq code how can I do so? 所以我试图在上面的Linq代码中做同样的事情,我该怎么做?

Very straightforward: use your param only if it is not null, and ignore otherwise. 非常简单:仅在您的参数不为null时使用它,否则将其忽略。

where
    CampusId == null || sr.CampusId == CampusId
    &&
    ClassId == null || sr.ClassId == ClassId

Assuming those are "sr" properties of course. 当然,假设这些是“ sr”属性。

This does not work with a ternary operator, because the query provider is not able to translate that to SQL. 这不适用于三元运算符,因为查询提供程序无法将其转换为SQL。
But if I understand your logic correct, you want to select records where @CampusId is null OR R.CampusId equals @CampusId . 但是,如果我理解您的逻辑正确,那么您想选择@CampusId为null或R.CampusId等于@CampusId So 所以

where 
(CampusId == null || CampusId == sr.CampusId) &&
(ClassId == null || ClassId == sr.ClassId)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM