DbComparisonExpression requires arguments with comparable types
16,507
Convert the entry of the number to an 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
}
or by using the C# 7.0 out variables feature:
if (searchTerm == null || Int32.TryParse(searchTerm, out int chartNo)) {
var model = db.Patient
.Where(r => searchTerm == null || r.ChartNumber == chartNo)
.Select(...);
return ...;
} else {
// Invalid number entered
}
Author by
dc922
Updated on June 29, 2022Comments
-
dc922 almost 2 years
I'm new to using Linq and am trying to create a search that will search by chart number and display the results in a new action view. When running the code I get the error "DbComparisonExpression requires arguments with comparable types". I believe this has something to do with the search type being string and chart number being int, but I'm not sure how to fix the problem. Any help would be greatly appreciated!
Controller:
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); }
Model:
public class NewListModel { public int ChartNumber { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
View:
@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> }
New controller
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 } }
-
dc922 about 10 yearsAdded in this logic and am now getting 'use of unassigned local variable 'chartNo'
-
Olivier Jacot-Descombes about 10 yearsThis can simply be fixed by initializing it with
0
. Please see my edited example.