1

I saw a lot of questions like this but seems I cant find anything to relate one to another and find solution for mine. I am using MVC 4 application where I have a dropdownlist with some values inside.

I am using viewbag to populate it.

ViewBag.Roles = new SelectList(db.Roles, "RoleId", "RoleName");

In the view my dropdown looks like this.

@Html.DropDownList("selectedRole", ViewBag.Roles as SelectList, String.Empty)

The string selectedRole is getting the RoleId value from the view.

After this I am doing some LINQ to the database with selectedRole which says that I cannot convert string to Int inside my LINQ which I really want so I can return better results.

     public ActionResult SearchResults(string selectedRole, string selectedCourse, string SearchParam)
        {
            var members = (from m in db.Members
                           select m);

            if (!String.IsNullOrEmpty(selectedRole))
            {
                members = (from m in db.Members
                           where m.UserRole == Int32.Parse(selectedRole)
                           select m);


            }
        //some more if's here...
        return View(members.ToList());
}

So the question is how to convert this selectedRole to Integer. Are there any rules to follow when converting in LINQ?

PS: I tried also Convert.ToInt32(selectedRole) which returns same error.

1
  • Saying "I receive an error" isn't enough. There are hundred of possible errors. You should write the error in the question. Commented Apr 26, 2015 at 18:16

1 Answer 1

3

In this case the question is irrelevant...

if (!String.IsNullOrEmpty(selectedRole))
{
    int selectedRole2 = Int32.Parse(selectedRole);

    members = (from m in db.Members
               where m.UserRole == selectedRole2
               select m);

You don't do it in linq, you do it outside.

In general, you aren't using only Linq, you are using Linq-to-Sql or Linq-to-Entities, because Members is a table. Sadly at least Linq-to-Entities doesn't have any cast method. You can obtain something similar by using a user defined function, but it is a little complex. Linq-to-Sql instead should support Convert.ToInt32 (see https://msdn.microsoft.com/en-us/library/vstudio/bb882655.aspx)

Sign up to request clarification or add additional context in comments.

1 Comment

Very simple solution, feeling dumb right now. I got on the same query the same error using Convert.ToInt32 so I doubt it supports any conversion at all.

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.