【发布时间】:2015-04-14 08:06:24
【问题描述】:
我有这个搜索词
[HttpPost]
public ActionResult Index(string searchString)
{
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.FIRST_NAME.Contains(searchString)
|| s.LAST_NAME.Contains(searchString)
|| s.PERSONAL_NUMBER.Contains(searchString)
|| s.ACD_UNI_DEGREES.DEGREE.Contains(searchString)
|| s.ACD_UNI_FACULTIES.FACULTY.Contains(searchString)
|| s.ACD_UNI_SPECIALIZATIONS.SPECIALIZATION.Contains(searchString)
|| SqlFunctions.StringConvert(s.SEMESTER).Contains(searchString)
|| s.COR_PAYER_STATUS.NAME.Contains(searchString)
|| SqlFunctions.StringConvert(s.CREDIT_COUNT).Contains(searchString));
}
return View(students.ToList());
}
但在调试时会抛出异常:
System.NotSupportedException:指定的方法'System.String StringConvert(System.Nullable`1[System.Decimal])' 关于类型 'System.Data.Objects.SqlClient.SqlFunctions' 无法翻译成 一个 LINQ to Entities 存储表达式。
问题出在这里:
SqlFunctions.StringConvert(s.SEMESTER).Contains(searchString)
SEMESTER 是十进制,searchString 是字符串。 我该如何改进呢?
【问题讨论】:
-
制作一个存储过程,将小数列转换为字符串并在服务器上进行“喜欢”比较。通过 SqlClient 调用存储过程
-
因为它可以为空,你可以先检查
s.SEMESTER != null && s.SEMESTER.HasValue然后s.SEMESTER.Value.ToString().Contains(searchString) -
你有什么样的数据库?
-
@默认是甲骨文。但我首先使用的是 EF db
-
好吧,您可以随时提前致电
.ToList(),然后进行进一步检查。但是根据documentation,你不能直接调用这个函数。此函数只能出现在 LINQ to Entities 查询中。因此您必须以其他方式编写逻辑(我猜是通过s.Semester.ToString()?)。所以.Where(s => s./* methods that can be translated*/).ToList().Where(s => s./* methods that cannot be translated*/);
标签: c# linq entity-framework