LINQ忽略带有方法语法的where子句

时间:2017-11-21 16:03:44

标签: c# linq

如果用户为这些值提供输入,我需要在查询中添加where子句。到目前为止,我正在尝试使用follow,但where子句被忽略。我的意思是,只有返回刘易斯姓氏的学生才会被退回,但结果并没有得到。

            var query = db.STUDENT
            .Where(x => x.STUDENT_CHANGE_IND == null);

        if (!string.IsNullOrEmpty(lastName)) query.Where(x => x.STUDENT_LAST_NAME.StartsWith("Lewis"));
        if (!string.IsNullOrEmpty(firstName)) query.Where(x => x.STUDENT_FIRST_NAME.StartsWith(firstName));
        if (!string.IsNullOrEmpty(spridenId)) query.Where(x => x.STUDENT_ID.Contains(spridenId));

        var y = query.Take(10).ToList();

我得到的结果是:

Student ID LastName

002 GUAR - HEMAR    
021 GUAR - Citibank SLC 
08092017    DO NOT USE 92 number mess up    
099 GUAR - ChaseJPM 
161 GUAR - WELLSG   
191 GUAR - TERI 

2 个答案:

答案 0 :(得分:7)

你需要说

query = query.Where(x => x.STUDENT_LAST_NAME.StartsWith("Lewis"));

而不仅仅是

query.Where(x => x.STUDENT_LAST_NAME.StartsWith("Lewis"));

答案 1 :(得分:2)

如果条款在单独的操作中被调用,那么它们不会堆叠。每次执行Where()语句时,您都需要保存新结果,以确保您使用已过滤的列表。

您更新的逻辑将如下所示:

var query = db.STUDENT.Where(x => x.STUDENT_CHANGE_IND == null);

if (!string.IsNullOrEmpty(lastName))
{
    query = query.Where(x => x.STUDENT_LAST_NAME.StartsWith("Lewis"));
}
if (!string.IsNullOrEmpty(firstName))
{
    query = query.Where(x => x.STUDENT_FIRST_NAME.StartsWith(firstName));
}
if (!string.IsNullOrEmpty(spridenId))
{
    query = query.Where(x => x.STUDENT_ID.Contains(spridenId));
}

var y = query.Take(10).ToList();