LIKE in OData query
I am converting a project from using linq2sql to use an odata source. I am trying to lookup a user like this...
FrameworkEntities db = new FrameworkEntities(
new Uri("http://localhost/odata/FrameworkService.svc"));
User user = db.Users.Where(
u => SqlMethods.Like(u.UserName, UserName)).FirstOrDefault();
but am getting the error "Method 'Boolean Like(System.String, System.String)' cannot be used on the client; it is only for translation to SQL." This was possible i开发者_高级运维n linq2sql so I am just wondering how I would change this so that it would work with the odata service. I haven't found any articles about it.
Like the error says, SqlMethods.Like() is for translation to SQL. oData queries don't get translated to SQL, so you can't use the method. Your best bet is to use IndexOf with StringComparison.InvariantCultureIgnoreCase
to emulate a case insensitive version of String.Contains
.
Oh...and you can combine your calls to :Where
and FirstOrDefault
User user = db.Users
.Where(u => u.UserName.IndexOf(Username,
StringComparison.InvariantCultureIgnoreCase) > 0)
.FirstOrDefault();
OData does contain a substringof function. For a small project I recently worked on, I was concerned if there was data 'LIKE' a string in three of the properties of the data model.
$filter=(IN_OUT eq '0' and (substringof('D20033', toupper(BENEFICIARY)) or substringof('D20033', toupper(ORIGINATOR)) or substringof('D20033', toupper(MEMO))))
I also used the toupper function around the model properties in conjunction with capitalizing the form-input search string so that I had a case-insensitive search. So here, I was worried about IN_OUT being '0' and 'D20033' in one or more of the three fields, BENEFICIARY, ORIGINATOR or MEMO.
Alternatively you can use 'startswith' Filter Expressions in Odata.
Example:
var query = context.Users;
query = query.AddQueryOption("$filter", String.Format("UserName startswith {0}", UserName));
Users sers = new DataServiceCollection<User>(query);
This will generate a URI like this: http://localhost:7048/OData/Users?$filter=UserName startswith 'Obama'
Reference: https://msdn.microsoft.com/en-us/library/hh169248(v=nav.80).aspx
精彩评论