Linq with optional Where clauses and Sql Server CE

时光总嘲笑我的痴心妄想 提交于 2020-01-01 10:48:15

问题


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

I am using Linq and Sql Server CE 4.0.

The linq code looks like the following ->

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

With Sql Server CE this throws the following error

"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."

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

FYI the following

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

gives me the error

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

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;

回答1:


Try this:

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.



来源:https://stackoverflow.com/questions/5136896/linq-with-optional-where-clauses-and-sql-server-ce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!