我是使用Linq的新手,我正在尝试创建一个按图表编号搜索的搜索,并在新的操作视图中显示结果。运行代码时,我得到错误" DbComparisonExpression需要具有可比类型的参数"。我认为这与搜索类型有关,字符串和图表编号为int,但我不确定如何解决问题。任何帮助将不胜感激!
控制器:
public ActionResult Index(string searchTerm = null)
{
var model =
db.Patient
.Where(r => searchTerm == null || r.ChartNumber.Equals(searchTerm))
.Select(r => new NewListModel
{
ChartNumber = r.ChartNumber,
FirstName = r.FirstName,
LastName = r.LastName,
}
);
return View(model);
}
型号:
public class NewListModel
{
public int ChartNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
查看:
@model IEnumerable<Project.Models.NewListModel>
@{
ViewBag.Title = "Home Page";
}
<form method="get">
<input type="search" name="searchTerm" />
<input type="submit" value="Search by Chart Number" />
</form>
@foreach (var item in Model)
{
<div>
<h4>@item.ChartNumber</h4>
</div>
<div>@item.FirstName</div>
<div>@item.LastName</div>
}
新控制器
public ActionResult Index(string searchTerm = null)
{
int chartNo;
if (searchTerm == null || Int32.TryParse(searchTerm, out chartNo)) {
var model = db.Patient
.Where(r => searchTerm == null || r.ChartNumber == chartNo)
.Select(r => new NewListModel
{
ChartNumber = r.ChartNumber,
FirstName = r.FirstName,
LastName = r.LastName,
}
);
return View(model);
} else {
//Invalid number entered
}
}
答案 0 :(得分:2)
将数字的条目转换为int
:
int chartNo = 0;
if (searchTerm == null || Int32.TryParse(searchTerm, out chartNo)) {
var model = db.Patient
.Where(r => searchTerm == null || r.ChartNumber == chartNo)
.Select(...);
return ...;
} else {
// Invalid number entered
}