我必须搜索cityname like '%United States;AK;Adak%'
所在的记录并在此基础上,将列的值存储在我的视图模型对象中。
我写了以下代码,当从一个数值进行强制转换时,它会导致一个错误,该数值必须小于无穷大。
zipcode=United States;AK;Adak;
var zipcd = (from u in db.ZipCodes1
where u.CityName.Contains(zipcode) && u.CityType == "D"
select u).ToList().Select(u => new Viewsearch
{
Zipcode = u.ZIPCode,
CityName = u.CityName,
stateabbr = u.StateAbbr
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 1)
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName;
}
else if (locations == "")
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName;
}
else
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName + "," + locations;
}
if (zipcd.Count() > 3)
{
locations = locations.Replace(locations, "," + "<br>");
}
编辑-这是与以前不同的错误消息吗?别介意
您的强制转换是错误的——您试图将查询的结果(可能有多个结果)强制转换为单个对象。
Viewsearch vs = (Viewsearch)zipcd;
您的zipcd
是IQueryable<Viewsearch>
,而不是Viewsearch
。如果您只期望一个结果或希望分别使用第一个结果,或者您需要根据返回的对象的IEnumerable/IQueryable来编写代码,则可以使用Single()
或First()
。