如何字符串转换可空INT LINQ [英] How to convert string to nullable int LINQ
问题描述
我看到了很多这样的问题,但似乎我不能找到任何关系彼此,找到我的解决方案。我使用MVC 4应用程序,我有里面的一些值一个DropDownList。
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.
我使用viewbag来填充它。
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)
字符串 selectedRole
从视图中获得角色ID
值。
在此之后,我做了一些LINQ到数据库 selectedRole
它说,我不能将字符串转换我的LINQ里面INT,我真的想这样我就可以返回更好的结果
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());
}
所以,问题是如何将这个 selectedRole
转换为整数。有没有什么规则在LINQ转换时要遵循?
So the question is how to convert this selectedRole
to Integer. Are there any rules to follow when converting in LINQ?
PS:我也试过 Convert.ToInt32(selectedRole)
返回相同的错误
PS: I tried also Convert.ToInt32(selectedRole)
which returns same error.
推荐答案
在这种情况下,这个问题是不相关的...
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);
您不这样做在LINQ,你外面去做。
You don't do it in linq, you do it outside.
在一般情况下,你是不是只使用LINQ中,你正在使用LINQ到SQL或LINQ到实体,因为成员
是一个表。可悲的是,至少LINQ到实体没有任何投法。您可以获得通过使用用户定义的函数类似的东西,但它是一个有点复杂。 LINQ到SQL,而不是应该支持 Convert.ToInt32
(见的 https://msdn.microsoft.com/en-us/library/vstudio/bb882655.aspx )
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)
这篇关于如何字符串转换可空INT LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!