Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbComparisonExpression requires arguments with comparable types

Tags:

c#

linq-to-sql

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 
            }
            }
like image 719
dc922 Avatar asked Apr 21 '14 15:04

dc922


1 Answers

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
}
like image 67
Olivier Jacot-Descombes Avatar answered Sep 29 '22 12:09

Olivier Jacot-Descombes