实体框架中的LIKE子句

时间:2011-06-03 12:43:12

标签: linq entity-framework

我必须搜索cityname like '%United States;AK;Adak%'的记录 并根据结果,在我的viewmodel对象中存储列的值。

我编写了以下代码,当从数字值转换必须小于无穷大时,它会导致错误。

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>");
}

1 个答案:

答案 0 :(得分:0)

编辑 - 这是一个与之前不同的错误消息?没关系

您的演员表错了 - 您正在尝试将查询结果(可能超过1个结果)转换为单个对象。

Viewsearch vs = (Viewsearch)zipcd;

您的zipcdIQueryable<Viewsearch>,而不是Viewsearch。如果您只期望1个结果或者想分别使用第一个结果,则可以使用Single()First(),或者您需要根据返回的IEnumerable / IQueryable对象编写代码。 / p>