views:

402

answers:

2

I'm trying to query the unique reference number of a table using Linq to Entities. The ID is provided via a textbox and hence a string in my code. Obviously in the database table the field is an integer so I have tried using .ToString first and then .Contains in the same way you would with a varchar(). This doesn't seem to work, with the error coming from the .ToString method.

How do you do this? I have tried converting the textboxes content to an integer but this then means the user would have to enter the exact int instead of a partial number.

Many Thanks

A: 
int value;
if(int.TryParse(someTextString,out value))
{
    //do work here using integer comparision with 'value'
}

Whatever do you mean by "partial" value? Whatever you are "adding" to the user supplied string, you can still do before you parse the value. Your explanation is not very clear.

If you are indeed trying to make a wildcard search, this will fail using Linq-to-entities against a DB int value. I doubt lte will make much sense of sometable.intvalue.ToString().Contains(). In this case, you might need to do some client side maths to figure out what ranges need retrieving, or to write a stored procedure that does the search at the SQL end..

spender
I guess he means he wants to be able to enter "12" and get "12" "121" and "1234" back... (and mayb even "312"?)
Benjol
A: 

I'm not sure why toString do not work for you. I've tried this to methods. Both returned answers:

List<int> ids = new List<int>() { 111, 211, 311, 422, 522, 622, 733, 833, 933 };
string query = "11";

var result = ids.Where(id => id.ToString().Contains(query));
var result2 = ids.ConvertAll<string>(i => i.ToString()).Where(id => id.Contains(query));
// Both return the first three items
HuBeZa
While the code will work fine for linq-to-objects as your code demonstrates, Linq-to-entities may not like this as it may not translate too well to SQL which is what the expression will be converted to in OPs case.
spender