我对使用decimal数据类型的搜索有疑问。我在表中有十进制数据类型,我必须在网格视图中调用,因为它的现有数据库和我没有权限更改数据库中的任何内容。我正在关注此链接 search decimal values in Linq query但是没有用。请告知我在哪里做错了。
这是我的观点
@using (Html.BeginForm("Index", "Incident", FormMethod.Post, new { id =
"SearchForm" }))
{
<button class="glyphicon glyphicon-search" style="width: 50px; height:
50px;"></button>
<input type="text" name="keyword" placeholder="Search..."
value="@Session["Search_Keyword"]" />
<br />
<br />
@Html.Grid(Model).Named("ITSMSearchGrid").Columns(x =>
{
x.Add(y => y.IncidentNumber).Titled("Incident Number");
x.Add(y => y.CreatedBy).Titled("Network Login");
x.Add(y => y.ProfileFullName).Titled("Full Name");
x.Add(y => y.Site);
x.Add(y => y.Subject);
x.Add(y => y.Service);
x.Add(y => y.OwnerTeam).Titled("Team Owner");
x.Add().Encoded(false)
.Sanitized(false)
.SetWidth(20)
.RenderValueAs(y => Html.ActionLink(" Details", "Details", new { id = y.RecId }, new { @class = "btn btn-primary fa fa-chevron-circle-down" }));
}).WithPaging(50).Sortable(true)
}
这是我的控制器
public ActionResult Index(string keyword)
{
List<Incident> incidentList = _context.Incidents.Where(x =>
x.TypeOfIncident == "Incident").ToList();
decimal dec;
bool IsDecimal = decimal.TryParse(keyword, out dec);
// Truncating search to 2 digits this should be equal to your db
// column precision so that rounding case are handled properly
decimal TruncateDigits = -1;
if (IsDecimal)
TruncateDigits = Convert.ToDecimal(Math.Truncate(dec * 100) / 100);
if (keyword == null)
{
if (Session["Search_Keyword"] != null)
{
keyword = (string) Session["Search_Keyword"];
}
else
{
return View(incidentList.OrderBy(x => x.IncidentNumber).ThenBy(x => x.CreatedBy).ToList());
}
}
else
{
Session["Search_Keyword"] = keyword;
}
return View((keyword == ""
? incidentList
: incidentList.Where(x =>
SqlFunctions.StringConvert(x.IncidentNumber).Contains(keyword.ToUpper())||
x.CreatedBy.ToUpper().Contains(keyword.ToUpper())
).ToList()).OrderBy(x => x.IncidentNumber).ToList());
// return View(incidentList);
}
这就是我的错误“System.NotSupportedException:只能从LINQ to Entities调用此函数。”
答案 0 :(得分:2)
错误消息非常清楚,您正在尝试在内存列表中调用SQL函数。将您的代码更改为:
if (!string.IsNullOrEmpty(keyword))
{
incidentList = incidentList
.Where(x => x.IncidentNumber.ToString().Contains(keyword.ToUpper())
|| x.CreatedBy.ToUpper().Contains(keyword.ToUpper())
.OrderBy(x => x.IncidentNumber)
.ToList();
}
return View(incidentList);
请注意,我在.ToList()
来电之前删除了.OrderBy
只是在浪费资源。