Linq带有可选的Where子句和Sql Server CE

Ken*_*130 5 linq sql-server-ce linq-to-sql

我有一个带有可选用户名字段的搜索表单.如果未提供用户名,则应返回所有匹配项.

我正在使用Linq和Sql Server CE 4.0.

linq代码如下所示 - >

from p in context.Accounts
where (name==string.Empty || p.UserName.Contains(name))
Run Code Online (Sandbox Code Playgroud)

使用Sql Server CE会引发以下错误

"此位置不允许使用参数.确保'@'符号位于有效位置,或者此SQL语句中的参数完全有效."

我可以采取其他方法在Linq中使用可选的Where子句吗?

仅供参考

from p in context.Accounts
where (string.IsNullOrEmpty(name) || p.UserName.Contains(name))
Run Code Online (Sandbox Code Playgroud)

给了我错误

"函数的指定参数值无效.[参数#= 1,函数名称(如果已知)= isnull]"}

这是因为Sql Server CE不支持IsNull.如果Name参数为Null,我只需执行以下操作.

if (name == null)
    name = string.Empty;
Run Code Online (Sandbox Code Playgroud)

Sam*_*eff 9

试试这个:

var query = from p in context.Accounts
            select p;

if (!string.IsNullOrEmpty(name)) {
    query = query.Where(p => p.UserName.Contains(name));
}
Run Code Online (Sandbox Code Playgroud)

没有规则说查询必须在单个语句中.您可以添加到现有查询,直到您实际执行它为止.

  • @ Kenoyer130您应该阅读一些关于LINQ延迟执行的内容,否则会出现您不会理解的意外和错误;) (2认同)