0

I am making a search index. I got it working pretty good but I cannot incorporate ItemID (item numbers) in my search because i am having trouble converting the String in the TextBox.Text to a int in order for it to be a comparable type.

var q = (from t0 in db.Item
         join t1 in db.Categories on t0.CategoryID equals t1.CategoryID
         join t2 in db.Divisions on t0.DivisionID equals t2.DivisionID
         where t0.DivisionID == DDLInt &&
         //Contains
         (t0.ItemName.Contains(txtSearch.Text.Trim()) ||
         t0.Email.Contains(txtSearch.Text.Trim()) ||
         t0.Description.Contains(txtSearch.Text.Trim()) ||
         t0.Phone.Contains(txtSearch.Text.Trim()) ||
         t0.ItemID.Equals(txtSearch.Text.Trim())) 
               // ^ This is the line where  
               //   it breaks because it is not a comparable type
         group t0 by new
         {

I am not sure how to convert or parse it and still have the search work properly.

2
  • I made a mistake sorry i am new. It is saying i am using Linq to Entities and not Linq to SQL with i am confused with that. But it is not letting me using the Parse or convert. Commented Oct 25, 2012 at 15:35
  • ` LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.` is the error message Commented Oct 25, 2012 at 15:40

5 Answers 5

3

Either parse the string to an int:

t0.ItemID.Equals(Convert.ToInt32(txtSearch.Text.Trim()))) 

or convert the int to a string:

t0.ItemID.ToString().Equals(txtSearch.Text.Trim())) 

or take the conversion out of the query:

int searchID;
if !int.TryParse(txtSearch.Text.Trim(),out searchID)
    searchID = -1;  // set to an invalid ID

var q = (from t0 in db.Item
     <snip>
     t0.ItemID.Equals(searchID)) 
Sign up to request clarification or add additional context in comments.

Comments

1

Should simply be:

t0.ItemID.Equals(int.Parse(txtSearch.Text.Trim()))

Comments

1
t0.ItemID.Equals(Int32.Parse(txtSearch.Text.Trim());

Comments

1

If you are sure that it will be a valid integer you can use int.Parse. If you are unsure if it's a valid integer you can use int.TryParse and possibly prompt the user to re-enter if it's not valid.

It is generally best to validate all items before building the query (check that numbers are numbers, dates are dates, choice values are a valid choice, etc.). If something is invalid you can save yourself a database query by checking it at the start.

Comments

1

You can use int.Parse

t0.ItemName.Contains(txtSearch.Text.Trim())

would be

int.Parse(t0.ItemName.Contains(txtSearch.Text.Trim()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.