0

I am trying to show all the data of t1 table in a gridview using Entity Framework but I am getting an error

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.

This is my code:

protected void Button2_Click(object sender, EventArgs e)
{
    var v = (from obj in de.t1
             where obj.Id == Convert.ToInt32(TextBox5.Text)
             select obj).ToList();
    GridView1.DataSource = v;
    GridView1.DataBind();
}
1
  • Maybe read the error message and try to overcome it. It clearly says that using the method ToInt32 isnt allowed so dont use it inside the query convert the string to int outside of the linq... Commented Jun 30, 2014 at 18:32

4 Answers 4

3

Entity Framework is trying to execute Convert.ToInt32(TextBox5.Text) on the SQL side, which it obviously cannot do.
So, introduce a temporary variable to store the result of conversion:

var tempId = Convert.ToInt32(TextBox5.Text);

Then pass it to the where clause:

...
where obj.Id == tempId
...
Sign up to request clarification or add additional context in comments.

Comments

0

The problem you are running into is the fact that the entity framework doesn't know how to translate Convert.ToInt32 into a valid SQL expression. Simply cast the textbox value to an integer before you query, and things should be fine.

protected void Button2_Click(object sender, EventArgs e)
{
    int id = Convert.ToInt32(TextBox5.Text);
    var v = (from obj in de.t1
             where obj.Id == id
             select obj).ToList();
    GridView1.DataSource = v;
    GridView1.DataBind();
}

Comments

0
protected void Button2_Click(object sender, EventArgs e)
{
    var objId = Convert.ToInt32(TextBox5.Text);
    var v = (from obj in de.t1
            where obj.Id == objId
            select obj).ToList();
    GridView1.DataSource = v;
    GridView1.DataBind();
}

1 Comment

Code only answers, which may well be a workable solution, are usually improved by some explanation. Please consider commenting or explaining how your suggested code works.
0
    protected void Button2_Click(object sender, EventArgs e)
        {
            var id = Convert.ToInt32(TextBox5.Text);
            var v = (from obj in de.t1
                    where obj.Id == id
                    select obj).ToList();
            GridView1.DataSource = v;
            GridView1.DataBind();
        }

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.