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

编程入门 行业动态 更新时间:2024-10-25 03:24:36
本文介绍了带有可选Where子句和SQL Server CE的Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have a search form with an optional User Name field. If the User Name is not supplied then all matches should be returned.

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

I am using Linq and Sql Server CE 4.0.

linq代码如下所示->

The linq code looks like the following ->

from p in context.Accounts where (name==string.Empty || p.UserName.Contains(name))

对于Sql Server CE,这会引发以下错误

With Sql Server CE this throws the following error

此位置不允许使用参数.请确保此SQL语句中的'@'符号位于有效位置或所有参数均有效."

"A parameter is not allowed in this location. Ensure that the '@' sign is in a valid location or that parameters are valid at all in this SQL statement."

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

Is there some other approach I can take to have optional Where clauses in Linq?

仅供参考

from p in context.Accounts where (string.IsNullOrEmpty(name) || p.UserName.Contains(name))

给我错误

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

"The specified argument value for the function is not valid. [ Argument # = 1,Name of function(if known) = isnull ]"}

这是由于Sql Server CE不支持IsNull.如果Name参数为Null,我将简单地执行以下操作.

This is due to Sql Server CE not supporting IsNull. I simply do the below if the Name parameter is Null.

if (name == null) name = string.Empty;

推荐答案

尝试一下:

var query = from p in context.Accounts select p; if (!string.IsNullOrEmpty(name)) { query = query.Where(p => p.UserName.Contains(name)); }

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

There's no rule saying the query has to be in a single statement. You can add on to an existing query up until the point you actually execute it.

更多推荐

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

本文发布于:2023-10-22 08:23:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1516974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子句   可选   SQL   Linq   CE

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!